Reputation: 297
I am making a Text RPG in C++ as a little project. However, I am having trouble getting my function to repeat if the user inputs "No" or an invalid input.
This is my function:
void name_type() {
bool running = true;
system("CLS");
while (running == true) {
std::string name, option;
std::cout << "What is your name?\n";
std::getline(std::cin, name);
// Up to here is not repeated.
system("CLS");
std::cout << "Are you sure this is your name?\n\nType 'Yes' if so.\nElse, type 'No'.\n";
std::cin >> option;
system("CLS");
if (option == "Yes" || option == "yes") {
std::cout << "Hello, " << name << "!\n";
running = false;
}
else if (option == "No" || option == "no") {
continue;
}
else {
continue;
}
}
}
The problem is that when I go through the function, it will only repeat anything after the comment if I type "no". If, however I type "yes", it works fine.
Can anyone explain what is happening, and how to fix it?
Upvotes: 0
Views: 63
Reputation: 1211
I see you use continue to keep the user in the name selection loop if he/she types 'No' or 'no'. Why not check for a yes instead?
bool running = true; // initialize 'running' to true
std::string name, option;
std::cout << "What is your name?\n";
std::getline(std::cin, name);
system("CLS");
std::cout << "Are you sure this is your name?\n\nType 'Yes' if so.\nElse, type 'No'.\n";
while(running == true){ // outer loop
std::cin >> option; // read in the option
while (!(option == "Yes" || option == "yes" )) { // inner loop
system("CLS");
if (!(option == "No" || option == "no" )) {
std::cout << "Invalid Input : Please enter Yes/No\n";
}
std::cout << "Are you sure this is your name?\n\nType 'Yes' if so.\nElse, type 'No'.\n";
} // check if the input is yes. if not, keep looping.
running = false; // if the input was yes, set running to false and exit the outer loop
}
That should cover any input other than Yes, and will loop unless the user says either 'Yes' or 'yes'.
Upvotes: 1
Reputation: 1290
The standard input stream is left with the \n (new line) created when you pressed 'enter' after typing 'No' or 'no'. For this reason, getline would immediately read an empty line, and right after that, you clear the screen. This made the impression of the code not executing again.
You can use cin.ignore to clear the stream from that new line. Also, you may want to consider using std::endl instead of \n when you print your messages.
void name_type() {
bool running = true;
system("CLS");
while (running) {
std::string name;
std::cout << "What is your name?" << std::endl;
std::getline(std::cin, name);
std::string option;
system("CLS");
std::cout << "Are you sure this is your name?" << std::endl;
std::cout << "Type 'Yes' if so." << std::endl;
std::cout << "Else, type 'No'." << std::endl;
std::cin >> option;
std::cin.ignore(1, '\n');
system("CLS");
if (option == "Yes" || option == "yes") {
std::cout << "Hello, " << name << "!" << std::endl;
running = false;
}
}
}
Upvotes: 1