C++ c+中的输入问题+;

C++ c+中的输入问题+;,c++,C++,我有一个非常基本的问题,我想从用户那里获取一定范围内的整数输入。如果用户给出的是字符串或字符而不是整数。然后我的程序进入无限循环 我的代码是这样的 cin >> intInput; while(intInput > 4 || intInput < 1 ){ cout << "WrongInput "<< endl; cin >> intInput; } cin>>输入; 而(输入大于4 | |输入小于1){ 不能输

我有一个非常基本的问题,我想从用户那里获取一定范围内的整数输入。如果用户给出的是字符串或字符而不是整数。然后我的程序进入无限循环

我的代码是这样的

cin >> intInput; 
while(intInput > 4 || intInput < 1 ){ 
   cout << "WrongInput "<< endl; 
   cin >> intInput; 
}
cin>>输入;
而(输入大于4 | |输入小于1){
不能输入;
}
<>我只允许使用C++库而不是C库。

中提到的,您应该检查每个循环中的<代码> CIN < /代码>的状态。< /P> 可能的实施:

if(cin >> intInput)
while(intInput > 4 || intInput < 1 ){ 
   cout << "WrongInput "<< endl; 
   if(!(cin >> intInput)){ break; } 
}
if(cin>>输入)
而(输入大于4 | |输入小于1){
无法输入){break;}
}
非常难看的代码,只是试图说明答案,即检查
cin

#include的状态
#include <locale>
..
if(!isalpha(intInput)) { 
..
}
.. 如果(!isalpha(intInput)){ .. }

注意,例如,如果用户输入“+”,这将不起作用,但它可能会将您引导到正确的方向

此答案的解决方案是始终从标准输入中读取

std::string input; int value = 0;
do
{
        // read the user's input. they typed a line, read a line.
    if ( !std::getline(std::cin,input) )
    {
        // could not read input, handle error!
    }

        // attemp conversion of input to integer.
    std::istringstream parser(input);
    if ( !(parser >> value) )
    {
        // input wasn't an integer, it's OK, we'll keep looping!
    }
}
    // start over
while ((value > 4) || (value < 1));
std::字符串输入;int值=0;
做
{
//读取用户的输入。他们键入一行,读取一行。
如果(!std::getline(std::cin,输入))
{
//无法读取输入,处理错误!
}
//尝试将输入转换为整数。
std::istringstream解析器(输入);
if(!(解析器>>值))
{
//输入不是整数,没关系,我们将继续循环!
}
}
//重新开始
而((值>4)| |(值<1));

Make that 26个问题可能重复。这里的问题到底是什么?不幸的是,这并不能真正检查初始读取是否成功:-(。您可能还应该清除标志,而不是在失败时中断循环&&!eof(输入字符串而不是数字时会发生这种情况).
intInput
显然是一个整数,因此不能对其使用
isalpha