C++:忽略第一个 cin.ignore 之后的输入



好的,所以这是我程序的一部分,在输入有效输入之前,它基本上是向用户重复出现的错误消息。所以基本上我面临的问题是,每当我输入一个无效的数字(例如 0、12 或负数(时,什么都不会输出,程序将等待另一个输入,只有这样它才会将输入识别为错误或有效输入。输入符号或字母时,这不是问题。我可以使用任何解决方法吗?

while (Choice1 < 1 || Choice1 > 11) 
{
if(!(cin >> Choice1), Choice1 < 1 || Choice1 > 11)
{   
cin.clear();
cin.ignore(512, 'n');
cout << "naError! Please enter a valid input!" << endl;
cout << "Now please enter the first code: ";
cin >> Choice1;
}
}

也许这就是您的意图:

#include <iostream>
#include <limits>
int main()
{
int Choice1{0};
while (!(std::cin >> Choice1) || Choice1 < 1 || Choice1 > 11) 
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
std::cout << "Error! Please enter a valid input!" << std::endl;
std::cout << "Now please enter the first code: " << std::endl;
}
return 0;
}

您可以在此处和/或此处阅读有关逗号运算符的信息,我发现逗号运算符不属于条件表达式的一部分。另外,我不认为你真的想要ifwhile循环进行范围界定。我做了一些额外的小改动,保留了大部分原始结构——这仍然可能需要一些工作。

相关内容

最新更新