gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:05:00 25 4
gpt4 key购买 nike

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

while (Choice1 < 1 || Choice1 > 11) 
{
if(!(cin >> Choice1), Choice1 < 1 || Choice1 > 11)
{
cin.clear();
cin.ignore(512, '\n');
cout << "\n\aError! 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;
}

您可以阅读 here和/或 here关于逗号运算符,我发现它不属于条件表达式的一部分。另外,我认为您并不真的希望 if 包含 while 循环。我做了一些额外的小改动,保留了大部分原始结构——仍然可以使用一些工作。

关于C++:在第一个 cin.ignore 之后忽略输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52076457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com