Simple C++

Started by
6 comments, last by Jasper_x 18 years, 10 months ago
I have a question about something im trying to do for a game. I'm starting small, a simple text based game involving "soldiers" and things, and I want to add the functionality to save. So what i'm going to do for the sake of learning how(I'm slowly adding more options and features and learning more C++ as I go, I thought that would be the best approach, learn things as I think of them until I have a semi-real game going). The # of soliders for each team(there's several types of soldiers, who do different things to the opposing player) is stored as a variable. SO When they want to save, the game will be creating a file with each value on a different line. Ex: # of P1's offensive soldiers # of P1's defensivr soldiers # of P1's assasains etc etc, with each of the line being a number, IE liek 100 350 75. I have the file output under control, like creating the file and putting the variables in the correct spots, but I'm confused on the read. How can I get my program to read one line of the text, input the data into a variable ( IE load it into a variable so they can start the game where they left off), and then go to the next line? I understand opening files, "\n" characters and all that, but i'm missing something or just not doing it right. As for examples, I've tried various methods but still can't get it to work. So basically, my question is: How do I make my program read one line of data from the save file, assign it to a variable in the game which has already been declared, then skip to the next line? If anyone has another method to accomplish the same thing, allowing the user(s) to save/load games, I'm open to suggestions. Later, and thanks in advance, -Nick Kennedy
Advertisement
I had the same problem (couldn't read numbers from a file)...

Go to this page in order to get the cDataPackage class...
http://www.gamedev.net/community/forums/topic.asp?topic_id=326612

Sorry, I don't remember how to post links... Just go to the bottom of the thread and copy the 'cDataPackage' class.

Using the source code for the 'cDataPackage' class, you can save and load numbers for your game. In your case, the code may look like this...

// Assumes that P1_OffensiveNum, P1_DefensiveNum, and P1_AssassinNum have been declaredvoid Save(){  /* Creates an instance of the cDataPackage class, the string in the brackets is the      key used for the encryption. */  cDataPackage DP("KEY");  // Stores all the variables inside the class  InputRaw(0, P1_OffensiveNum);  InputRaw(1, P1_DefensiveNum);  InputRaw(2, P1_AssassinNum);    // Your numbers will be saved in the file "SAVE.txt" - don't worry if you can't read it,  // as the WriteFile function will encrypt the numbers so users can't alter their save  // data.  DP.WriteFile("SAVE.txt");}void Load(){  /* The key for the DP object MUST be the same as the one used for saving the file,      otherwise you will have trouble reading it!! */  cDataPackage DP("KEY");    // Read numbers back into the cDataPackage class  DP.ReadFile("SAVE.txt");  // Extract the numbers from the class  P1_OffensiveNum = ExtractRaw(0);  P1_DefensiveNum = ExtractRaw(1);  P1_AssassinNum = ExtractRaw(2);}


My save routine operates differently than yours. When writing the file, it seperates the numbers with a "|" character instead of writing seperate numbers on each line.

Whatever you do with the numbers after you load them is up to you. I hope this helps!
Here's a bit of code that should do the trick.

ifstream SavedGame; //this creates an input file object

SavedGame.open("savedfilename.txt"); //this actually opens the file you are trying to read

SavedGame >> Defensive_Soldiers; /*this will put info into your variable Defensive_Soldiers- it reads data until it finds whitespace characters- in your case, a newline*/
//add more for each line you want to read

SavedGame.close(); //this closes the file

I haven't done C++ in a long time, so I can't guarantee this is perfect. I sure hope it helps you, though!
-----------------------------Weeks of programming can save you hours of planning.There are 10 kinds of people in this world-- those who understand binary and those who don't.
Hey, thanks a lot! I'll go try that now, and I'm assuming it will work, the encrypted numbers is a good addition too I was thinking of that earlier on but thought I'd start out easy. Anywayz, thanks again and I'll let you know how it goes. =),

-Sir Dragon's Fang
The easiest way to save/load numbers from a file is to use a fstream object. Using your example, somthing like this should work:
#include <fstream>class Statistics{public:	bool LoadFromFile(const char * fileName);	bool SaveToFile(const char * fileName);private:	unsigned int offensiveSoldiers, defensiveSoldiers, assassins;};bool Statistics::LoadFromFile(const char * fileName){	std::ifstream file(fileName); //Open up the file	if (!file)		return false; //We failed	file >> offensiveSoldiers >> defensiveSoldiers >> assassins;	return file.good(); //If everything worked OK, then file will be in a good state}bool Statistics::SaveToFile(const char * fileName){	std::ofstream file(fileName); //Open up the file, but for writing this time	if (!file)		return false; //We failed	//We need to add whitespace between the numbers, otherwise we'll get 10035075 as one number when reading it back	//I'm using a newline here, but you could use a space (' ') or a tab ('\t') instead	file << offensiveSoldiers << std::endl;	file << defensiveSoldiers << std::endl;	file << assassins << std::endl;	return file.good(); //If everything worked OK, then file will be in a good state}

If you wanted to use exceptions, then the functions could be void and you could set the fstream obects to throw an exception.
Hey thanks guys it worked great. Unfortunately, I screwed up on the code for asking the user if they want to load it or not. What I'm trying to do is make a comparison between a char variable and a character but it's giving me errors. I know it's a silly question and I'm just missing something little but I'd like to figure it out. Basically it goes like this:

char sv_ld //save_load
cout << "Would you like to load a previously saved game?(y/n)\n";
cin >> sv_ld;
if (sv_ld == "y") {

load();

}

and the code down here just goes to the game if they select no. The problem is I can't figure out how to make the comparison and im eally confused right now. So please just tell me what I'm missing and then I'll be happy. =),

-Nick Kennedy
Are you just missing a semicolon after the first line? Try this

char sv_ld; //save_load

and see if that works. Actually, those double quotes might also need to be single quotes. Double quotes makes it a string, which will tack the null terminator onto the end of the string. Since your variable is only one character, there's no room for the null terminator. Try this

if (sv_ld == 'y'){

too and then you should be good to go.

[Edited by - sofsenint on June 19, 2005 11:26:12 AM]
-----------------------------Weeks of programming can save you hours of planning.There are 10 kinds of people in this world-- those who understand binary and those who don't.
I had the semi-colon, I actually just retyped the code for the post. And the siongle quotes works! I actually just thought of that myself in the middle of church, I almost smacked myself hehe. Thanks a lot,

-Nick Kennedy

This topic is closed to new replies.

Advertisement