Link to home
Start Free TrialLog in
Avatar of VEngineer
VEngineer

asked on

reading in variable number of objects per line


For each line in my textfile, I can have either two, three, or four floats.  So the file looks somehwhat like:

1.2 1.0 9.9
1.2 34.4
4.9 3.2 7.0 3.2
1.2 34.4 3.2
4.9 3.2 7.0 3.2
1.2 1.0 9.9


I have a struct that has 4 fields in it - and I want to read in the first number into the first field, the second number into the second field, and the third and fourth numbers in to their respective fields if they exist.

How do I read in this type of a file easiest using cin (not fscanf)?  I thought about using getline(), but that means I have to perform string to float conversions don't I?  So is there an easier way?

Avatar of arnond
arnond

Try this:

---------------------------------------------------------
struct WhatEverYouCallYourStruct ReadLine()
{
 char tmp1[100],tmp2[100],tmp3[100],tmp4[100;
 struct WhateverYouCallYourStruct s;

 cin>>s.a;
 cin>>s.b;
 cin>>tmp3;
 if (!strcmp(tmp3,"\n"))
{
  s.c=0;
  s.d=0;  
  return (s);
}
 else
{
  s.c=atof(tmp3);
}
cin>>tmp4;
 if (!strcmp(tmp4,"\n"))
{
  s.d=0;  
  return (s);
}
 else
{
  s.d=atof(tmp4);
}
 return (s);
}
--------------------------------------------------

Note: this isn't tested so there may be a few bugs in it.

Hope this helps,
Arnon David.

Avatar of VEngineer

ASKER

doesn't cin skip over spaces and \n characters?

assume we have only two numbers on the first line

cin>>s.a;   // reads in the first num
cin>>s.b;   // reads in the second num
cin>>tmp3;  // reads in the first num on the next line

So I can't see how to get around this..
 
in that case, after reading the first 2 numbers, would parse char by char, into a temp array. If I get a number, fine, assgin it to s.c if I get a '\n', assgin 0 to s.c and s.d. (and so on for the fourth number).
Of course, you should do the converting of the string to double (but that's easy).
to read a single char from cin, use the cin.get() function.

Arnon David.
ASKER CERTIFIED SOLUTION
Avatar of LucHoltkamp
LucHoltkamp

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
How do you justify getting 256 characters?  What happens if the line happens to exceed 256 characters?