Question

No matter what I try, I cant get the following code to work correctly.

ifstream inFile;
inFile.open("sampleplanet");
cout << (inFile.good()); //prints a 1
int levelLW = 0;
int numLevels = 0;
inFile >> levelLW >> numLevels;
cout << (inFile.good()); //prints a 0

at the first cout << (inFile.good());, it prints a 1 and at the second a 0. Which tells me that the file is opening correctly, but inFile is failing as soon as read in from it. The file has more then enough lines/characters, so there is no way I have tried to read past the end of the file by that point.

File contents:

8
2
#level 2
XXXXXXXX
X......X
X..X..XX
X.X....X
X..XX..X
XXXX...X
X...T..X
XXX..XXX
#level 1
XXXXXXXX
X......X
X..X.XXX
X.X..X.X
X..XX..X
X......X
X^....SX
XXX.^XXX
Was it helpful?

Solution 2

It turned out to be an issue with X-Code. I created a project in net beans using the same exact code and had no problems. Weird.

Update: In my X-Code project, I changed my active SDK from Mac OS 10.6 to Mac OS 10.5 and everything works fine now.

OTHER TIPS

It's a known bug. From Xcode 3.2.1's Release Notes:

The default gcc 4.2 compiler is not compatible with the Standard C++ Library Debug Mode. C++ programs compiled with Xcode 3.2 may not work in the Debug configuration. To fix this, set the Compiler Version to 4.0, or edit the Debug configuration’s Preprocessor Macros and remove the entries:
_GLIBCXX_DEBUG=1 _GLIBCXX_DEBUG_PEDANTIC=1

I reproduced and tested your code and file and my output was 11 and both levelLW and numLevels were set as expected. I would definitely take a hard look at hidden characters in your file (or lack thereof). I like to use Notepad++ with "Show all characters" enabled. My file is exactly what you posted with a carriage return and a linefeed at the end of each line.

You said the first inFile.good() prints out 1. That should mean the file opened OK. Because you said "it works through the terminal but not XCode" in tehMick post - for what it's worth - when I tested this, I ran into the following problem: my IDE (C++Builder) runs the program out of a DEBUG directory (when you are in debug mode). I needed to place "sampleplanet" in the DEBUG directory or use a path in the open that found the file like "..\\sampleplanet".

+MyProjectDirectory
|  mymain.cpp (Even though this is where I had the source file..)
|  sampleplanet
+--DebugDirectory
     mymain.obj
     mymain.exe (the program runs out of this directory.)

Once I took care of the above issue everything worked as expected using the above code and file. I checked the file in Notepadd++ to confirm the [CR][LF] after every line. If you create the file in Linux, it may have only [LF] however (I did everything under Windows).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top