Good day! I'm a beginner in programming C++ language so pardon me for my question. The scenario: I'm asking the user if he/she wants a drink. The only answer the user can type is 'Y' for yes and 'N' for no then there comes the final dialogue. I made the answer a char: char answer;
then added an if statement. If the user types Y or N, everything's fine. However, whenever the user types Y(+ any letter) such as (YHTY), the program still accepts it (same goes for N). I just need a single letter answer Y or N and other answer beyond that would lead to the else dialogue.
这是代码:
#include <iostream>
using namespace std;
int main()
{
char answer;
cout << "Do you want a drink? " << endl;
cout << "Y/N: ";
cin >> answer;
if(answer == 'Y' || answer == 'y'){
cout << "Okay. I'll bring you some." << endl;
} else if(answer == 'N' || answer == 'n'){
cout << "Okay suit yourself." << endl;
} else{
cout << "Please type just Y/N." << endl;
}
return 0;
}
由于要处理多个字符,因此必须使变量成为字符串。例如
getline
reads a single line of text, and puts it in a string.尽管这完全符合您的要求,但可能并不完全符合您的要求。假设用户键入空格键,然后键入Y,那么我希望将其与输入Y完全一样,但是上述代码将拒绝任何带有空格的输入。输入验证始终比您想像的要难,作为初学者,真的不值得浪费您的时间(IMHO)。