File stream reading line with specific criteria

classA, (-7, 11) // classA requires 2 variables(x,y)
classB, (5, -31, -22) // classB requires 3 variables(x,y,z)
classC, (-7, 11), (20, -1) // classC requires 4 variables in the described format(x1,y1,x2,y2)


Assuming the above text file data,
How would I go about extracting the integer values to construct the class object itself?

Rough idea
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
ifstream infile;
string classType,rubbish;
string x,y,z;

while(getline(infile,classType,','))
{
 if (classType == "classA")
   {
       // do specific format input stream and stoi conversion
       getline(infile,rubbish,'(');
       getline(infile,x,',');
       getline(infile,rubbish,' ');
       getline(infile,y,')');
       ClassA aObj(stoi(x),stoi(y));
   }
 else if (classType == "classB")
   {
       // do specific format input stream and stoi conversion
       getline(infile,rubbish,'(');
       getline(infile,x,',');
       getline(infile,rubbish,' ');
       getline(infile,y,',');
       getline(infile,rubbish,' ');
       getline(infile,z,')');
   }
 else if (classType == "classC")
   {
       // do specific format input stream and stoi conversion

   }
}
Last edited on
> Assuming the above text file data,
¿the comments are also part of the input file?

> code below doesnt work
it's commented, that's why it does nothing
if you uncomment it it will work (extract the x, y values)

If you do not observe that behaviour, you need to be clearer with your issue, ¿how does it now work?
I suppose that you didn't try to use `aObj' outside of the if scope.
Sorry for not clarifying earlier. It works for the first loop and creates the object of class A but as it goes onto the second loop, the value of classType is changed to "classB" but it does not enter the conditional if statement preventing the object of class B to be created.

The program is supposed to retrieve data for different classes displayed in a specific format. As the loop runs,within each if statement, the object is instantiated and stored in a vector to be implemented later.
Last edited on
After reading the data for a particular line, extract and discard the rest of that line.
1
2
3
4
5
6
7
8
9
10
11
12
if (classType == "classA")
   {
       // do specific format input stream and stoi conversion
       getline(infile,rubbish,'(');
       getline(infile,x,',');
       getline(infile,rubbish,' ');
       getline(infile,y,')');
       ClassA aObj(stoi(x),stoi(y));

       infile.ignore( 1000000, '\n' ) ; // throw the rest of this line away 
   }
   // etc. 


You may want to check for input errors; ie. handle badly formed lines.
Topic archived. No new replies allowed.