所以这是我的代码:
b:
cout << "\nDo you want to continue (Y/N)? ";
cin >> ans;
if (ans == 'y' || ans == 'Y')
goto a;
else if (ans == 'n' || ans == 'N')
goto c;
else
cout << "Invalid Answer!";
goto b;
我的问题是,如果我输入2个或更多的字母,它会全部读取并抛出&#34;无效答案!&#34;和打印&#34;你想继续(y / n)&#34;和我输入的字母一样多。喜欢这个
Do you want to continue (Y/N)? asd
Invalid Answer!
Do you want to continue (Y/N)? Invalid Answer!
Do you want to continue (Y/N)? Invalid Answer!
Do you want to continue (Y/N)?
答案 0 :(得分:0)
您的代码正在阅读每个字符并显示每个字符的结果,我认为将其作为字符串读取并获取第一个字符将解决它但我建议使用getch()
答案 1 :(得分:0)
你应该添加:
std::cin.clear();
std::cin.ignore(INT_MAX);
清除输入。 在您的情况下,您的代码应该成为:
b:
cout << "\nDo you want to continue (Y/N)? ";
cin >> ans;
if (ans == 'y' || ans == 'Y')
goto a;
else if (ans == 'n' || ans == 'N')
goto c;
else
cout << "Invalid Answer!";
cin.clear();
cin.ignore(INT_MAX);
goto b;