Problem with reading and printing from a text file

Hi everyone,

I'm trying to read in a file with Microsoft Visual C++ 2010 and print it. The problem is it prints the last line twice. This is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
int main()
{
   ifstream inFile;
   string inFileName = "test.txt";
   inFile.open(inFileName);

   if (inFile.is_open())
   {
	string line;
	while (inFile)
	{
            getline(inFile, line);
	    cout << line << endl;
            if (!inFile)
		break;
	}
	inFile.close();
   }
   else
   {
	cout <<"Could not open file" << endl;
   }
   system ("pause");
   return 0;
}


The content in the original text file is:
Hello There
123

And the output that the program showed me was:
Hello There
123
123


Can someone please explain why I'm having this problem? Thanks in advance.
Last edited on
Hello Song Tung,

The problem is here
1
2
getline(inFile, line);
cout << line << endl;

getline can fail if you already reached the last line of the file. But you don't check the state of the stream until after you print the line.

The best way to solve this would be to put getline as the condition of the loop itself. This will stop the loop as soon as getline fails, and eliminates the need for redundant safety checks.

1
2
3
4
while (getline(inFile, line))
{
    cout << line << "\n";
}


See how I formatted my code? Please do the same to your code, you can edit your post, highlight your code, and press the "<>" button under Format options.
Last edited on
Thanks a lot, Ganado and I'll try to format my code like the way you did
Happy to help, thanks!
Last edited on
Registered users can post here. Sign in or register to post.