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

Recommended Answers

All 3 Replies

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.

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

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 */
 }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.