data file handling output problem

i made a txt file & added some text to it

when i opened it from a c++ code to display the data, it's printing the whole thing correctly, but the problem is that the last line is printed twice

why is it doing so??

example:
if i make a txt file from windows named 'fruits.txt' & fill in:
"apple
banana
orange

"
& then open it in the following program:
1
2
3
4
5
6
7
8
9
10
11
12
#include<iostream.h>
#include<fstream.h>
int main()
{
	fstream file("fruits.txt", ios::in);
	char *a=new char;
	while(!file.eof())
	{
		file>>a;
		cout<<a<<"\n";
	}
}  


the output is this
apple
banana
orange
orange





but now if i remove the last blank line from the txt file, the output becomes
apple
banana
orange



why is the last line being repeated, if the txt file has a blank line at the end???
It works fine for me. I used this to test it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ofstream ff;
    ff.open("fruits.txt");
    ff << "apple\nbananna\norange";
    ff.close();

   fstream file("fruits.txt", ios::in);
   char *a=new char;
   while(!file.eof())
   {
	file>>a;
	cout<<a<<"\n";
   }
}
Last edited on
yeah, ur's will work
BUT if u change 1 line, u'll get to know my problem

just replace ff << "apple\nbananna\norange";
by ff << "apple\nbananna\norange\n";

& u'll get that output sort of output which troubles me!
moreover, u used a pointer to display the contents & that's nice
but if u display be passing file's content to a char type variable & then display it, u'll get the error even in ur current program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ofstream ff;
    ff.open("fruits.txt");
    ff << "apple\nbananna\norange";
    ff.close();

   fstream file("fruits.txt", ios::in);

   char a;

   while(!file.eof())
   {
	file>>a;
	cout<<a<<"\n";
   }
}



plzzzzz try to rectify this one, coz this is beginning to give me a headache!
moreover, u used a pointer
Which I copied from your code..

But here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    ofstream ff;
    ff.open("fruits.txt");
    ff << "apple\nbananna\norange";
    ff.close();

   fstream file("fruits.txt", ios::in);
   string a;
   while(!file.eof())
   {
	file>>a;
	cout<<a<<"\n";
   }
}
Looping on eof is almost always the wrong thing to do.

file >> a; failing will often be the trigger that sets the eof bit in the stream. When file >> a; fails, cout<<a<<"\n"; is still executed as if file>>a; was successful.

The solution is fairly simple: don't loop on eof.

1
2
while ( file >> a )
    cout << a << '\n' ;
Topic archived. No new replies allowed.