有人可以向我解释为什么当用户在询问时为 int 菜单变量输入 char 时我的代码不会导致无限循环或崩溃吗?我已经对其进行了测试,它确实可以正常工作,但本以为它会崩溃……非常感谢!
int menu;
int drawCheck = 0;
cout << "Press 1 to play a friend\n";
cout << "Press 0 if for some reason you opened this and now dont want to play...\n";
cin >> menu;
while (menu!= 1) //User enters a number that isnt 1
{
if(menu ==0)
{
exit(EXIT_SUCCESS); //When user enters 0 the program will exit
}
cout << "Please enter either 1 to play a friend or 0 to exit: "; //Will ask untill player enters either 1 or 0
cin >> menu;
}
最佳答案
I have tested it and it does work correctly...
我不确定您如何声称它所做的是“正确的”...如果用户键入一个字母 - 继续还是终止,什么是正确的?为什么?
无论如何,鉴于...
int menu;
cin >> menu;
从 C++11 开始,如果将 cin
中的 int
解析为 menu
失败,menu
根据 22.4.2.1.2/3 设置为零:
The numeric value to be stored can be one of:
— zero, if the conversion function fails to convert the entire field. ios_base::failbit is assigned to err.
...(other behaviours for successful parsing num that's in/out of range)...
因此,对于 C++11,输入字母对 menu
的影响与输入 0
的影响相同,都会导致程序退出。
在 C++11 之前,解析失败后 menu
的值将是未定义的(即使它已被初始化),导致后续使用 menu
未定义行为。你无法推断未定义的行为将如何表现出来,尽管 - 在程序的某些特定执行时 - 它可能恰好与你希望发生的事情相匹配。
关于c++ - 为什么这段代码不会使 cin 崩溃?为 int 变量输入的 char C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35979062/