why its happen......

i use matlab to get the data.....after that i write the data in text file.......and i already read the data in text file using c++?

data in my file have only :-
0
1
2


when i use code below :-

ifstream input("test.txt"); //put your program together with thsi file in the same folder.

if(input.is_open()){

while(!input.eof()){
string number;
int data;
getline(input,number); //read number
data = atoi(number.c_str()); //convert to integer
cout<<data<<endl; //print it out
}

}



why cout display :-
0
1
2
0

eof() only becomes true after you have already tried and failed to read from the file (which would cause a 0 to be output). Loop on the status of the stream instead.
what i need to do?.....i just want read :-
0
1
2
ibnu wrote:
what i need to do?

You need to get rid of whatever taught you to write "while(!input.eof())"

As for the program, change it to:

1
2
3
4
5
6
ifstream input("test.txt");
string number;
while(getline(input,number)) { 
    int data = atoi(number.c_str()); 
    cout << data << '\n';
}

or, to keep the local string from polluting the function scope,

1
2
3
4
5
ifstream input("test.txt");
for(string number; getline(input,number); ) { 
    int data = atoi(number.c_str()); 
    cout << data << '\n';
}


or, if your compiler is reasonably modern,

1
2
3
4
5
ifstream input("test.txt");
for(string number; getline(input,number); ) { 
    int data = stoi(number); 
    cout << data << '\n';
}
Last edited on
tqvm.......:)
Topic archived. No new replies allowed.