1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

Working with Files in C++ Question

Discussion in 'Mac Programming' started by robert17, Jul 17, 2006.

  1. macrumors newbie

    I am learning C++ and have encountered troubles trying to read data from a file into my program. The program is meant to read an integer value from a text file and print it to the screen. It prints a number to the screen, but it is definitely not the one from the file (12 v. -1880995964). I using XCode version 2.3 with Mac OS 10.4.6. I have tried various methods, but assume that I am creating a new file, selecting "Empty File in Project" and naming it "input.txt". My code is as follows:

    #include <iostream>
    #include <fstream>
    using namespace std;
    int main () 
         int num;
         ifstream inData;
         inData >> num;
         cout << num;
        return 0;
    There is nothing in the text file except for the number "12". I appreciate any help that you can give!

  2. macrumors 68020


    is there a newline char after the 12?

    there probably should be. :)
  3. macrumors newbie

    I tried adding the '\n' after the 12, but it still gave me "-1880995964". Thanks.
  4. macrumors 68020


    Manually adding \n won't do it. What I meant was, did you hit return after the 12? That'll write the newline char to the file (which C++ will read properly).

    I haven't used C++ in a while (nor do I have gcc installed at the moment), so I'm not much help. Sorry.
  5. macrumors newbie

    Ah, ok. I went ahead and tried that too, but it gave the same results. Thanks for the try.
  6. macrumors regular

    You should initialize the variable num to 0 (or some other value) before reading the file. If you run your program and it returns 0 instead of 12, you have a problem reading the file.

    I suspect your problem is that the program can't find the file input.txt. The program looks in the working directory for the file, and if the file is not in that directory, the program won't be able to open the file. Xcode initially sets the working directory to your Build Products directory which is the following directory:


    BuildConfiguration will be either Debug or Release. Either move the input.txt file to the Build Products directory or specify the full path to the file in your code instead of just the name input.txt.
  7. macrumors member


    use the ifstream::good() method to check if you opened the file successfully before attempting to read from it
  8. macrumors newbie

    Much thanks Mark. I initialized num and it came back as zero so I moved the file and it worked properly. I appreciate the help!

Share This Page