Reading text file - extra line
Help. Anyone tell me why this code outputs 7 lines (the last line twice) while the file contains 6 lines?
cout << "read msgfile\n";
ifstream msgfile ("script1.msg");
while (msgfile.good()) //if not at end of file, continue reading
{
// load vector with deffile
msgfile >> line;
vectormsgfile.push_back (line);
cout << line << "\n";
}
msgfile.close();
Cheers and tx
Re: Reading text file - extra line
Because immediately after reading the last line, msgfile.good() still returns true. Only after the next attempted read does it return false, but by then you would have pushed back into the container again and printed the line.
As such, it would be better to write say:
Code:
cout << "read msgfile\n";
ifstream msgfile("script1.msg");
while (getline(msgfile, line))
{
// load vector with deffile
vectormsgfile.push_back(line);
cout << line << "\n";
}
msgfile.close();
Re: Reading text file - extra line