Please try:
int x;
while(file >> x;) {
std::cout << x << std::endl;
}
For better understanding Please go through this.
Hope this will help you.
سؤال
I found a strange behavior with std::ifstream (or more probably I'm missing something on how to properly use it). I have the following program:
#include <iostream>
#include <fstream>
int main(int argc, char** argv) {
std::ifstream file;
file.open(argv[1]);
while(not file.eof()) {
int x;
file >> x;
std::cout << x << std::endl;
}
return 0;
}
I call it on a file that contains numbers separated by spaces, like the following:
1 34 567 3
The program outputs:
1
34
567
3
3
The last number is always duplicated. I guess it's because it does not reach EOF after reading the last number, it reaches the mandatory '\n' of text files, and the next file >> x gives me again the last read number.
How can I properly detect that there is no more number to read?
المحلول
Please try:
int x;
while(file >> x;) {
std::cout << x << std::endl;
}
For better understanding Please go through this.
Hope this will help you.