-
February 9th, 2012, 05:36 PM
#1
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
-
February 9th, 2012, 09:01 PM
#2
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();
-
February 10th, 2012, 04:05 AM
#3
Re: Reading text file - extra line
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|