How To Read A Text File And Save It


jkgp2x

Still Fresh
Joined
Feb 7, 2006
Messages
32
i want to have my game read a script from a text file and be able to compare it to other chars and ints. I have been using fgets to get the info from the file but i can never compare the info from the file to make events happen. How would i compare this info to other variables. I'm not very experienced with c++ so any help would be nice.

Edit: i guess i should give an example of what im trying to do
textfile
image.jpg
stuff.jpg
etc.

code:
std::vector<SDL_Surface> gameImages;
char line[30];

while(fgets(line, 30, pFile) != NULL)
{
//loadImage takes a const char as parameter and returns a surface
gameImages.push_back(loadImage(line, -1));
}


i cant get this to work along with other similar actions
 
jkgp2x said:
CODE

std::vector<SDL_Surface> gameImages;
char line[30];

while(fgets(line, 30, pFile) != NULL) {
//loadImage takes a const char as parameter and returns a surface
gameImages.push_back(loadImage(line, -1));
}
i cant get this to work along with other similar actions

you should go for a vector with SDL_Surface*;
Your current code copies the full surface from loadImage to the vector, you don't want your poor GP2X to do that ;)

what exactly goes wrong with your code?
 
Last edited by a moderator:
Text file:
CODE
abc.png
cdf.png
rtegd.png


Code:
CODE
std::vector<SDL_Surface> gameImages;
std::string filename = "";
ifstream fin("data.txt");
while( fin >> filename )
{
gameImages.push_back( loadImage( filename.c_str(), -1 ));
}


Edit: As Atgast said, pointers are better to store in this case.
 
yaustar's way should work, but remember that '>>' also breaks on spaces, so
CODE
bla die bla.bmp
somethingelse.bmp

would crash, but is easily avoided by not using spaces in filenames.
 
when i do it Yaustar's way the program still just crashes. Does that have anything to do with the line endings or something.
 
jkgp2x said:
when i do it Yaustar's way the program still just crashes. Does that have anything to do with the line endings or something.
Since Yaustar's way automatically strips \r | \n you really should not have any problems with that.
Perhaps you could show the file you are trying to parse?
 
Last edited by a moderator:
How are you returning the SDL_surface?

If you're using IMG_Load or SDL_LoadBMP, they return an SDL_Surface* or NULL if it can't load the file.

If it's returning NULL and you dereference it, it will crash.
 
Yaustars way did work i just typed it in wrong. Thanks a lot guys. you save me a lot of time.
 
Back
Top