所以出于某种原因,无论我进入这个If-Else语句,它返回"程序已中止",好像我输入了错误的请求答案...非常困惑,我似乎无法在网站周围找到任何相关内容!
int ch;
cout << "Do you have any extra credit points? (Enter Y/y or N/n)" << endl;
cin >> ch;
int ExtraCredit;
if (ch == 'Y' || ch== 'y')
{
cout << "Enter the number of extra credit points: ";
cin >> ExtraCredit
}
else if (ch!='n' || ch!='N' || ch != 'y' || ch != 'Y')
{
ExtraCredit=0;
cout<< Invalid entry. Program Aborted." << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题很早就出现了:
int ch; // are you sure this should be an int?
cout << "Do you have any extra credit points? (Enter Y/y or N/n)" << endl;
cin >> ch;
Run Code Online (Sandbox Code Playgroud)
cin在int类型变量上char的行为与在s 上的行为不同.当您在键盘上输入"y"或"n"时,cin将失败.
您可以cin通过调用其fail()方法来检查是否失败,如下所示:
int num;
std::cout << "Enter a number: ";
std::cin >> num;
if (std::cin.fail()) {
std::cout << ":(" << std::endl;
} else {
std::cout << "Your number was " << num << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |