ifstream/ofstream to save variables
Hi
I am haphazardly learning C++ on my own/through tutorials
I am trying to write a program that has you input values, writes those values to a .txt file, and then can read them/assign them back to the variables if you execute it again (i.e. saving/loading)
The relevant pieces of code are
Code:
#include<iostream>
#include<fstream>
#define screensize 25
using namespace std;
void clearScreen()
{
for (int x = 0; x < screensize; x++)
cout << "\n";
return;
}
class Hero
{
public:
string name;
int hp;
int mp;
int gold;
int exp;
int level;
void setName (string x)
{
name = x;
return;
}
void setValues (int a, int b, int c, int d, int e)
{
hp = a;
mp = b;
gold = c;
exp = d;
level = e;
return;
}
void showStats()
{
clearScreen();
cout << "\t\t\tSTATS" << endl;
cout << "Name : " << name << endl;
cout << "Level: " << level << endl;
cout << "HP: " << hp << endl;
cout << "MP: " << mp << endl;
cout << "EXP: " << exp << endl;
cout << "Gold: " << gold << endl;
cout << "<Press enter to return!>";
cin.get();
return;
}
};
void saveGame(Hero player)
{
ofstream save ("save.txt", ios::trunc);
save << player.name << " ";
save << player.hp << " ";
save << player.mp << " ";
save << player.gold << " ";
save << player.exp << " ";
save << player.level << " ";
save.close();
return;
}
void loadGame(Hero player)
{
string x;
int a, b, c, d, e;
ifstream load ("save.txt");
load >> x >> a >> b >> c >> d >> e;
player.setName(x);
player.setValues(a, b, c, d, e);
load.close();
player.showStats();
return;
}
int main()
{
clearScreen();
Hero player;
cout << "1. Start" << endl;
cout << "2. Load" << endl;
int selection;
cin >> selection;
switch (selection)
{
case 1:
clearScreen();
cout << "Name: ";
cin >> player.name;
cout << "Level: ";
cin >> player.level;
cout << "HP: ";
cin >> player.hp;
cout << "MP: ";
cin >> player.mp;
cout << "Gold: ";
cin >> player.gold;
cout << "EXP: ";
cin >> player.exp;
cout << "<Press enter to check your stats page!>";
cin.get();
cin.get();
player.showStats();
clearScreen();
cout << "Saving stats...";
saveGame(player);
break;
case 2:
loadGame(player);
break;
}
}
Now this works, however
If I call player.showStats() from main instead of loadGame, like so
Code:
case 2:
loadGame(player);
player.showStats();
break;
It outputs (seemingly) random large values instead of the ones previously set
What does this mean :o