Need some help here~

Why does the last output will come out twice?
Let say my name.txt contains "David John James Denise", the output for Denise will come out twice.
Any explanation is appreciated. Thx.
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
26
27
28
#include<iostream>
#include<fstream>
#include<string>
using namespace std;


int main()
{
	fstream dFile;
	string name;
	dFile.open("name.txt",ios::in);
	if(!dFile)
	{
		cout<<"Error.\n";
	}
	else
	{
		while(dFile.good())
		{
			dFile>>name;
			cout<<name<<endl;	
		}
	}
	dFile.close();
	system("pause");
	return 0;
}
It's a very common problem... because the variable "name" still has a value when the pointer reaches the end of the file. Try this:

1
2
3
4
5
6
		while(dFile)
		{
			dFile>>name;
			cout<<name<<endl;	
		}


or this:

1
2
3
4
5
6
7
		while(dFile.good())
		{
			dFile>>name;
                        if(dFile.good())
			    cout<<name<<endl;	
		}


One of them should work :)

And please, next time write a subject to your problem that indicates what the problem could be... "need some help here" is not a valid subject... 99% of the people who come here need help :)
Last edited on
The second part works but not the first part.

Thanks and will do.
This also works and is more compact
1
2
3
4
while(dFile>>name)
{
	cout<<name<<endl;	
}


Read here for why: http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5
I see. Thanks for the info.
Topic archived. No new replies allowed.