Why can not I enter integers from a file?

advertisements

I'm trying to get this C++ code to input a series of numbers from a text file:

    int x = 0;
    cin >> x;

    ifstream iffer;
    int numbers[12];
    iffer.open("input.txt");
    for (int i = 0; i < 12; i++){
        iffer >> numbers[i];
    }

This doesn't seem to work on the Mac. Every cell will equal to 0 regardless of the values in the text file. In other words, the ifstream isn't assigning the numbers.

How can I make this work? Is it a Mac issue and if so, how can I get it to work?

Thanks!

Anthony Glyadchenko


I tried your code, slightly modified, on both Linux (g++ 3.4.4) and Mac (g++ 4.0.1) and it works just fine!

With respect to Chuck, if input.txt does not exist, iffer.fail() is true. Since you say that's not the case...

Another possibility is a different input.txt file than what you expected. If it had too few numbers, you'd see zeros (or other garbage values). (You could test with iffer.eof(), though that might be set (appropriately) after reading the last number if there's no trailing whitespace (like a newline). So test eof() before reading!)

Alternatively, you could have a dangling pointer elsewhere in your code trashing something inappropriately. Sometimes adding and removing large chunks of code will permit you to manually "binary search" for where such problems actually lie.

#include <iostream>
#include <fstream>

using namespace std;

#define SHOW(X) cout << # X " = \"" << (X) << "\"" << endl

int main()
{
  int x = 0;
  cin >> x;

  ifstream iffer;
  int numbers[12];
  iffer.open("input.txt");
  SHOW( iffer.fail() );
  SHOW( iffer.eof() );
  for (int i = 0; i < 12; ++i)
  {
    SHOW(i);
    SHOW(numbers[i]);
    iffer >> numbers[i];
    SHOW(numbers[i]) << endl;
  }
  for (int i = 0; i < 12; ++i)
    SHOW(numbers[i]);
  SHOW( iffer.fail() );
  SHOW( iffer.eof() );
}