简体   繁体   English

想逐行读取,但fstream只读取第一行

[英]Want to read line by line but fstream read only first line

A very simple program: read a file line by line (each line contains integer) then do something and write the output to a file. 一个非常简单的程序:逐行读取文件(每行包含整数),然后执行某些操作并将输出写入文件。

int main()
{
  ifstream fin ("f:\in.txt");
  ofstream fout ("f:\out.txt");

  int a;
  while (fin >> a) {
      int b = (a >> 6) & 255;
      fout << b << endl;
  }
  return 0;
}  

The input as multiple lines like this: 输入为多行,如下所示:

93859312
2635577168
2929619024
312396812
3019231016
3139200356
...

But the while loops is iterated only one time!! 但是while循环仅迭代一次! and output only contains 并且输出仅包含

183

Which corresponds to the first input line. 对应于第一条输入线。 Why??? 为什么???

The numbers after the first one are larger than an int can represent. 第一个数字之后的数字大于int可以表示的数字。

Instead of int a; 代替int a; , use long long int a; ,使用long long int a;

The largest value than an int can represent is 2,147,483,647: What is the maximum value for an int32? 一个int可以代表的最大值是2,147,483,647: int32的最大值是多少?

Your first value is less than this, but your second is not. 您的第一个值小于此值,但第二个则不然。 Thus (fin >> a) fails (ie is not true), and your program exits from the while loop. 因此(fin >> a)失败(即不是真的),并且您的程序从while循环中退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM