Game loads

Aug 16, 2012 at 3:50pm
Hi everyone,
I'm creating this simple word based game that has saves. I put the names of the saves each on a seperate line on a file that the program creates. This following code is supposed to make the user type in the name of the save he wants to load.
1
2
3
4
5
6
7
8
9
10
11
12
13
string name;
string load;
cin >> load;
ifstream loads;
loads.open("Loads.txt");
findinfo:
getline(loads, name);
if(name == load)
{
	getInfo(load);
}
else
	goto findinfo;

But for some reason, when I run the program and am promted for the load I want to open, when I click enter, it prompts me for something else. Is there a problem with this code?
Aug 16, 2012 at 4:12pm
post the code from where it calls it.
Aug 16, 2012 at 5:37pm
Yes, post the code that calls it.

Also, I suggest a revision of what's above:

1
2
3
4
5
6
7
8
9
10
11
12
13
string load;
cin >> load;
cin.sync(); // This makes sure anything not extracted into load is discarded.

ifstream loads;
loads.open("Loads.txt");

string name;
do {
	getline(loads, name);
} while (name != load);

getInfo(load);


Avoid using goto statements to make your code more readable.
Aug 16, 2012 at 7:42pm
Your program only checks the name on one line at a time:

An example save file:
1
2
3
John
Mary
Frank

At the time of the first prompt name equals "John", so an input of Mary or Frank continues the loop. The second prompt now has name equal "Mary", so you've lost your chance to play as John.

When you get to the end of your file you can only choose the last name or your program loops forever.

Another approach might be to read every line first, and then print:
Save Games:
1) John
2) Mary
3) Frank
Please make your choice: ...

Your validation becomes ensuring that the user hits 1, 2, or 3.

Last edited on Aug 16, 2012 at 7:42pm
Topic archived. No new replies allowed.