Help with file I/O

Hello CPP! I'm new to this forum but I'm hoping I can start contributing at later times. I need some help with a certain program of mine. It saves 3 integers, nBank, nWallet and yes. When it loads, I want it to read the values, at the moment it's only reading the first value(Well, outputting it anyway).
Save function
1
2
3
4
5
6
7
8
9
10
11
	int save() {
    std::ofstream save("data.dat");
	if (!save) {
		std::cout << "Failed to save.";
		return -1;
	}
	save << nBank << std::endl;
	save << nWallet << std::endl;
	save << yes << std::endl;
	return 1;
}



Read function
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  	int read() {
		using namespace std;
		ifstream read("data.dat", ios::in | ios::out);
		if (!read) {
			return -1;
		}
		while(!read.failbit) {
string a, b, c;
read.seekg(0,ios::beg);
getline(read, a);
cout << a << endl;
read.seekg(1,ios::beg);
getline(read, b);
cout << b << endl;
read.seekg(2,ios::beg);
getline(read, c);
cout << c << endl;
		}

		return 1;
	}

data.dat
1
2
3
500
500
1

Also, if possible, could you give me advice on how to get these numbers into integers straight away so I don't need to convert from string to int?
Last edited on
do u want to reuse the saved values of nBank, nWallet, yes and assign them to some other integers when the program loads or just output them
I would like to reuse the saved values.
So, say the game had saved 500
30
1
I'd like to make nBank = 500, nWallet = 30 and yes = 1
In line 3 of read you open an input stream for output. Don't do that.

Your compiler probably warns you that in line 7 of read the conditional expression that controls your loop is constant (in other words it will always evaluate to true.) One shouldn't, as a general rule, use seekg on text files.

1
2
3
4
5
6
7
8
9
10
11
12
13
void read() 
{
    std::ifstream in("data.dat") ;

    int a, b, c ;

    while ( in >> a >> b >> c )
    {
        std::cout << "a: " << a << '\n' ;
        std::cout << "b: " << b << '\n' ;
        std::cout << "c: " << c << '\n' ;
    }
}
Topic archived. No new replies allowed.