In the following I present a code that is not working as intended. It should be given a name, and then an age if the users chooses to give it, in order to finally print both to stdout. Following the code you will see my teacher's own run of the code. What I don't understand is why the expression get_yes_or_no("Would you tell me how old are you? ")
evaluates to true when my teacher answers correctly "no". Even though I know there are some obvious mistakes in my code, as it is for the semantically wrong if (age)
statement, what I'm really interested about and I don't understand is why my teacher was prompted her age after inputing "no".
#include <iostream>
#include <string>
bool get_yes_or_no(std::string question);
int main() {
using std::cout;
using std::cin;
std::string result{};
cout << "Input your name: ";
std::getline(cin, result);
int age{ 0 };
if (get_yes_or_no("Would you tell me how old are you? ")) {
cout << "Input your age: ";
cin >> age;
}
if (age)
cout << "Your name: " << result << ", your age: " << age << std::endl;
else
cout << "Your name: " << result << std::endl;
return 0;
}
bool get_yes_or_no(std::string question)
{
std::string result{};
std::cout << question << '\n' << "Answer yes or no: ";
std::cin >> result;
if (result == "yes")
return true;
else if (result == "no")
return false;
else {
std::cout << "The only valid answers are \"yes\" or \"no\".\n";
return get_yes_or_no(question);
}
return -1;
}
My teacher's run:
Input your name: Io Would you tell me how old are you? Answer yes or no: nope The only valid answers are "yes" or "no". Would you tell me how old are you? Answer yes or no: no Input your age: no Your name: Io