1

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!! and output only contains

183

Which corresponds to the first input line. Why???

mahmood
  • 23,197
  • 49
  • 147
  • 242

1 Answers1

8

The numbers after the first one are larger than an int can represent.

Instead of int a;, use 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?

Your first value is less than this, but your second is not. Thus (fin >> a) fails (i.e. is not true), and your program exits from the while loop.

Community
  • 1
  • 1
maditya
  • 8,626
  • 2
  • 28
  • 28
  • @JesseGood Actually, that's right. Also, I removed my upvote because the answerer makes assumption about the size of an `int`. That's not good. –  Mar 30 '13 at 08:42
  • Fair enough. @JesseGood, care to make it a full answer? A getline would be useful here ... – maditya Mar 30 '13 at 08:44
  • 1
    Maybe it's both the size of the number as well as a newline problem (though I suspect its the size of the number). The question is tagged visual-studio-2010 and on that platform 2635577168 is too large to read into an int so the `fin >> a` will fail on the second line of input. However, `long int` is no help (it has the same range as `int` on that platform). You'll need to move to `long long int` or similar to read in the larger numbers. – Michael Burr Mar 30 '13 at 08:51
  • And after a little testing, VS 2010 doesn't have a problem with Unix (or old Mac) style line endings for this program (though that's not necessarily the case in general). The problem is with trying to read large int values into a type that can't represent them, as maditya indicated. – Michael Burr Mar 30 '13 at 08:56
  • 1
    @maditya: just change your suggestion from `long int` to `long long int` - your answer is pretty much correct except for that detail. The problem is not related to newlines. – Michael Burr Mar 30 '13 at 08:57
  • Will do. Thanks for investigating! – maditya Mar 30 '13 at 08:58