0

In C++, I am trying to read through a file and store the strings from that file into a string in the program. This works great until I get to the last word, which is always stored twice.

ifstream inputStream;
string next = "";
string allMsg = "";
inputStream.open(fileName.c_str());
string x;

while (!inputStream.eof())
{
    inputStream >> x;
    next = next + " " + x;
}
cout << "The entire message, unparsed, is: " << next << endl;

Doing this adds the last word or int from the file I open to next. Any suggestions? Thanks!

  • 3
    [`while (!eof())` is wrong.](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – chris Oct 15 '13 at 00:39

3 Answers3

3

This is because when you read the last line, it won't set eof bit and the fail bit, only when you read the END, eof bit is set and eof() returns true.

while (!inputStream.eof())  // at the eof, but eof() is still false
{
    inputStream >> x;  // this fails and you are using the last x
    next = next + " " + x;
}

change it to

while( inputStream >> x){
    // inputStream >> x;  dont call this again!
    next = next + " " + x;
}
Zac Wrangler
  • 1,330
  • 8
  • 8
0
while (!inputStream.eof())

Should be

while (inputStream >> x)
Zac Howland
  • 15,149
  • 1
  • 23
  • 37
  • @0x499602D2 - that has already been answered many many times: http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Zac Howland Oct 15 '13 at 02:22
-1

eof() will return true if the last read hit the end of file, not if the next read will hit the end of file. Try:

ifstream inputStream;
string next = "";
string allMsg = "";
inputStream.open(fileName.c_str());
string x;

inputStream >> x;
if(!inputStream.eof()) {
    do {
        next = next + " " + x;
        inputStream >> x;
    } while (!inputStream.eof())
}
cout << "The entire message, unparsed, is: " << next << endl;
Darius Makaitis
  • 850
  • 1
  • 5
  • 5