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.
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?
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.
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.