Trying to make a savegame.

So I made an RPG last couple of days and looking for a way to make it save...
I know I should use input/output file but I just don't understand the tutorial here on the site. What's the best way to save variables to a file, so that it can load them the next time the program starts?
This works:
1
2
3
4
5
std::ofstream ofs("save.txt");

ofs << variable1 << '\n';
ofs << variable2 << '\n';
ofs << variable3 << '\n';
what is ofs? I thought it was something like
myfile<< variable 1 <<"\n"
And for loading it again?
Galik wrote:
std::ofstream ofs("save.txt");

You can name it "myfile" if you want.

To load it again, just do the opposite:
1
2
3
std::ifstream ifs("save.txt");

ifs >> variable1 >> variable2 >> variable3;
Last edited on
Don't there need to be "\n" in between them?
Similar problem discussed here:
http://cplusplus.com/forum/beginner/28026/
xander333 wrote:
Don't there need to be "\n" in between them?

Not when reading them back in. The >> will automatically skip over the whitespace characters ('\n' or space or tab etc..).

For basic types, use the method filip showed you. For strings, use std::getline(). Like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int variable1 = 5;
std::string variable2 = "A right bright moonlit night.";
double variable 3 = 2.7;

std::ofstream ofs("save.txt");

ofs << variable1 << '\n';
ofs << variable2 << '\n';
ofs << variable3 << '\n';
ofs.close();

std::ifstream ifs("save.txt");

ifs >> variable1;
std::getline(ifs, variable2);
ifs >> variable3;


The reason being that >> will stop reading when it reaches a space. So if a string has spaces in it you need std::getline() to read the whole thing.
Last edited on
@Galik
The won't work. operator>> leaves the '\n' in the stream, so the getline() call will actually return an empty string.
use ifs.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); before calling getline on line15.
Good point.
Topic archived. No new replies allowed.