2

I'm trying to read in the text from a file and this is what I am doing:

int main(int argc, char* argv[])
{

ifstream inFile;
inFile.open(argv[1]);

string item;

while(inFile.good())
{
  inFile >> item;
  cout << item << " " << endl;
}

For some reason it will read the last word in the file twice. I tried using a count variable to keep track of how many times it enters the while loop and it always enters one time more then the total number of line in the file. I think this is happening because the inFile.good() statement is not returning false soon enough. How can if fix it?

Isabel Alphonse
  • 539
  • 1
  • 8
  • 14

3 Answers3

4

You are not testing if the

inFile >> item;

Is succeeding -- at the point of having read the last word of the file there is still a newline or some other blank space -- so you have not reached end-of-file, but on the other hand there are no more words to be read either, so the last read fails, but you are not detecting it.

You can test the success of the >> as a bool-expression, this should work;

if (inFile >> item)
   cout << item << " " << endl;
Soren
  • 14,402
  • 4
  • 41
  • 67
  • So what can I do to catch it? I tried setting `inFile >> item;` as the parameter but now it skips the first line and still reads the last line twice. – Isabel Alphonse Oct 16 '15 at 21:59
  • It will return a bool value true or false, just test that with an if-statment – Soren Oct 16 '15 at 22:01
1

The last read fails but you don't catch it. The variable just retains the previous value.

Change your loop to:

while(inFile >> item)
{
  cout << item << " " << endl;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

Other people have shown the code you should have written, so I'm just going to explain why your code didn't work.

istream.good(), indeed, "is not returning false soon enough." It will still be true after you have read the last item in the file. It only becomes false when you attempt to read one item past the end of the file.

All the various ways of asking the question "have I reached the end of the file?" in C and C++ have the same semantics. This is because the underlying OS primitive, read, cannot return data and signal EOF at the same time.

zwol
  • 135,547
  • 38
  • 252
  • 361