Thursday 6 December 2018

c++ - same word added twice





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!


Answer



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;
}


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...