开发者

C++ Simple file reading

开发者 https://www.devze.com 2022-12-08 16:29 出处:网络
I have a file,named f1.txt, whose contents are 75 15 85 35 60 50 45 70 Here is my code to read each integer and print them.

I have a file,named f1.txt, whose contents are 75 15 85 35 60 50 45 70

Here is my code to read each integer and print them.

#include <iostream>
#include <fstream>

using namespace std;
int main(int argc, char *argv[])
{
  fstream file("f1.txt", ios::in);
  int i;
  while(!file.eof()) {
    file >> i;
    cout << i << " ";
 }

return 0;
}

But when I compiled and run the pr开发者_StackOverflow社区ogram, the output is 75 15 85 35 60 50 45 70 70. Why it is reading the last integer twice ? Any clues ?


Try:

while(file >> i)
    cout << i << " ";


std::stream doesn't set eof() until a read fails, so one fix is:

while (file >> i, !file.eof()) cout << i << " ";
0

精彩评论

暂无评论...
验证码 换一张
取 消