因此,出于某种原因,无论我在此If-Else语句中输入什么,它都会返回" Program Aborted"好像我输入了错误的请求答案......非常困惑,我似乎无法在网站周围找到任何相关内容!
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;
}
答案 0 :(得分:6)
问题很早就出现了:
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;
cin
在int
类型变量上的行为与在char
上的行为不同。当您在键盘上输入“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;
}
答案 1 :(得分:1)
ints and chars are separate types, even though they can be compared based on the ASCII value of the char in C++. Because they are defined as separate types, when your code gets to the line cin >> ch
and ch
is of type int, it waits for something to be entered. The prompt tells the user to enter a char, and they do. The code sees the char, and as it wasn't an int, nothing is read in and the value of ch
is correctly determined by your code to be not y, Y, n, or N. If you'd like to cin
a char, declare char ch;
. If you'd like to have an int, prompt the user to enter a number.