Reputation: 35
Im having a bit of problem with getline. I want to read line by line but only the >> reading is working while the getline doesnt read. Here is my code:
int studentSize;
string programme;
filein >> studentSize;
filein >> programme;
if (programme == "Physics")
{
for(int i=0; i < studentSize; i++)
{
getline (filein,namephys, '*');
filein >> idphys;
getline (filein,course, '*');
filein >> mark;
phys.push_back(new physics());
phys[i]->setNameId(namephys, idphys);
phys[i]->addCourse(course, mark);
sRecord[idphys] = phys[i];
}
}
And here is my file:
2
Physics
Mark Dale*
7961050
Quantum Programming*
99
The output for Mark Dale and Quantum Programming doesnt work well. It seems to be getting the whole line before them. Thank you for your help.
Upvotes: 1
Views: 459
Reputation:
A stream might fail at any time & your loop has no way of reacting to it. You should do something like this :
if( programme == "Physics" )
{
filein.ignore();
// a more strict version is : (#include <limits>)
//filein.ignore( numeric_limits<streamsize>::max(), '\n' );
while( getline(filein, namephys, '*') &&
filein >> idphys &&
filein.ignore() && //** ignore the trailing newline (operator>> doesn't read it)
getline(filein, course, '*') &&
filein >> mark &&
filein.ignore() )
{
/* do something */
}
}
This loop immediately exits whenever the stream state becomes bad
Upvotes: 1