PDA

View Full Version : Working with Files in C++ Question




robert17
Jul 17, 2006, 08:13 PM
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.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



ChrisBrightwell
Jul 17, 2006, 08:21 PM
is there a newline char after the 12?

there probably should be. :)

robert17
Jul 17, 2006, 08:31 PM
I tried adding the '\n' after the 12, but it still gave me "-1880995964". Thanks.

ChrisBrightwell
Jul 17, 2006, 08:34 PM
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
Jul 17, 2006, 08:56 PM
Ah, ok. I went ahead and tried that too, but it gave the same results. Thanks for the try.

szymczyk
Jul 18, 2006, 01:30 PM
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.

SamMiller0
Jul 18, 2006, 04:24 PM
use the ifstream::good() method to check if you opened the file successfully before attempting to read from it

robert17
Jul 18, 2006, 05:03 PM
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!