Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

robert17

macrumors newbie
Original poster
Jul 17, 2006
4
0
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:

Code:
#include <iostream>
#include <fstream>

using namespace std;

int main () 
{

     int num;
     ifstream inData;

     inData.open("input.txt");

     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!

Robert
 

robert17

macrumors newbie
Original poster
Jul 17, 2006
4
0
I tried adding the '\n' after the 12, but it still gave me "-1880995964". Thanks.
 

ChrisBrightwell

macrumors 68020
Apr 5, 2004
2,294
0
Huntsville, AL
robert17 said:
I tried adding the '\n' after the 12, but it still gave me "-1880995964". Thanks.
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.
 

robert17

macrumors newbie
Original poster
Jul 17, 2006
4
0
Ah, ok. I went ahead and tried that too, but it gave the same results. Thanks for the try.
 

szymczyk

macrumors regular
Mar 5, 2006
187
17
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:

ProjectName/build/BuildConfiguration

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.
 

robert17

macrumors newbie
Original poster
Jul 17, 2006
4
0
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!
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.