problem with file

P

Paolo

Why does this stupid code read twice last number??? Tnx

#include <stdlib.h>
#include <iostream>
#include <fstream>

using namespace std;

int main ( )
{

int number;
ofstream testfile ( "test.txt" , ios::app);

cout<<"Insert a number, ctrl+z to end"<<endl;

while(cin>>number){
testfile<<number<<endl;
cout<<"Insert a number, ctrl + z to end"<<endl;
}

testfile.close();


cout<<"Reading number(s)from file..."<<endl;

ifstream testfile2 ("test.txt" , ios::in );

while(!testfile2.eof()){
testfile2>>number;
cout<<number<<endl;
}



system ("pause");
}
 
D

Dietmar Kuehl

Paolo said:
Why does this stupid code read twice last number???

Probably because it is, as you said, stupid! Of course,
you might find out the yourself as this question was
answered quite frequently but here is key problem anyway:
The stream does not know a priori whether an operation
will fail. Thus, you should always check the stream after
your operation: you did it right in the first loop, you
did it wrong in the second.
 
P

Paolo

Il Fri, 14 Jan 2005 11:11:47 -0500, Victor Bazarov
IIRC, there was a bug in Microsoft's I/O code. Try looking in the
archives for "read last line twice" or something like that.

Thank you, I solved :)
 
P

Paolo

Il 14 Jan 2005 08:15:37 -0800, "Dietmar Kuehl"
Probably because it is, as you said, stupid! Of course,
you might find out the yourself as this question was
answered quite frequently but here is key problem anyway:
The stream does not know a priori whether an operation
will fail. Thus, you should always check the stream after
your operation: you did it right in the first loop, you
did it wrong in the second.

Thank u, solved in this way:

while(testfile2>>number) {
cout<<number<<endl;
}
 
D

David Harmon

On Fri, 14 Jan 2005 17:04:11 +0100 in comp.lang.c++, Paolo
Why does this stupid code read twice last number??? Tnx ....
while(!testfile2.eof()){

This issue is covered in Marshall Cline's C++ FAQ. See the topic
"[15.5] Why does my input seem to process past the end of file?" It is
always good to check the FAQ before posting. You can get the FAQ at:
http://www.parashift.com/c++-faq-lite/
 

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,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top