this code display text file not correctly

C

chat

Hi,

I write program for writing and reading text file like this

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile("test.txt");
for(int i=0;i<5;i++) outfile<<i<<endl;
outfile.close();

ifstream infile("test.txt");
int a;
while(infile) {
infile>>a;
cout<<a<<endl;

}
infile.close(); return 0;
}

The result is this
0
1
2
3
4
4

Can anybody tell me what is the mistake in my program. It should show 0
1 2 3 4 (only one 4).
Why does it show digit 4 two times? (this code was compile with vc++ 6)
Thank you in advance.
chat watchara
 
A

Andre Kostur

Hi,

I write program for writing and reading text file like this

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile("test.txt");
for(int i=0;i<5;i++) outfile<<i<<endl;
outfile.close();

ifstream infile("test.txt");
int a;
while(infile) {
infile>>a;

You don't check to see if this extraction succeeded. If it fails...
cout<<a<<endl;

....This line displays whatever a contained the last time around.
 
C

chat

How to correct this program in order to show result correctly?
thank you very much.
chat watchara
 
C

chat

David Harmon à¢Õ¹:
while(infile >> a)

You are cool. Your suggestion work well. thank you very much.
But I still want to know why my program does not work?

chat watchara
 
J

Jim Langston

David Harmon à¢Õ¹:

How do you know which variable (infile or a) will used for condition
entering into while loop.

intfile >> a
returns a stream reference (istream I think, maybe something else) which has
a bool override so can be used as a bool in an if statement which returns
false if the stream is in a bad state. It will be in a bad state if some
conditions occur, such as trying to read "x" into an int, or hitting the end
of file.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,045
Latest member
DRCM

Latest Threads

Top