0

For example, I have 2 classes A[x,y,z] and B[a,b] and one vector for each class.
I want to read a text file containing data with my two classes
For example the text file may contain:
A [1,2,3]
B [1,2]
A [4,5,6]

How do i read in this file such that the 1st line will be stored as an instance of class A, 2nd line B, 3rd line A again(depending on the file)?

If the file only contains one object(A) i can do a overload operator and

ifstream fileIn( "test.txt" );
while (fileIn >> x >> y>> z) {
//create object A and call push_back on the vector.
}

but I'm having trouble with different objects

Edited by icebirdy: n/a

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by firstPerson
0

So you need to perform a check. Something like so :

while(fileIn){
 const char peekChar = fileIn.peek();
 switch(peekChar){
   'A': createObjectA(fileIn); break;
   'B': createObjectB(fileIn); break;
   default: /* error, object not supported */ break;
 }
}

cin.peek() just peeks at the next character but doesn't 'read' it. So you can use that to your advantage.

Edited by firstPerson: n/a

0

but peek doesnt work if my classes are named longer than a single char, right?
i.e. PosA PosB

0

Ok. So then you would have to parse the string :

string line;
while(getline(fileIn,line)){
 //assume each class is in its own line
 if(line.find("PosA") != string::npos){
    createObjectA(line);
 }else if(line.find("PosB") != string::npos){
    createObjectB(line);
 }else{
   /* error object not recognized */
 }
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.