检查输入是否不是整数或数字cpp

时间:2018-11-03 23:18:03

标签: c++ integer infinite-loop cin

我已经创建了一个猜谜游戏,您必须猜出从1到100范围内的随机生成的数字。如果用户输入的数字超出范围并且需要新输入,我还设法限制了用户。问题是当您不小心输入字母或符号时。然后进入无限循环。我尝试过:

while(x<1 || x>100 || cin.fail())//1. tried to test if input failed (AFAIU it checks if input is expected type and if it is not it fails)
while(x<1 || x>100 || x>='a' && x<='z' || x>='A' && <='Z') // 2. tried to test for letters at least
while(x<1 || x>100 x!=(int)x)//3. to test if it is not integer
{ cout<<"Out of range";
  cin>>x;
}

1 个答案:

答案 0 :(得分:2)

对于一种解决方案,您可以尝试使用isdigit。这将检查输入是否实际上是数字。因此,您可以执行以下操作:

if(!(isdigit(x))){
   cout << "That is not an acceptable entry. \n";
   continue;
}

编辑:我应该说,在研究了这一点之后,我意识到要使isdigit起作用,该条目必须是一个字符。但是,如果在发现char是int之后将char转换为int,这仍然可以工作。示例:

if(!(isdigit(x))){
       cout << "That is not an acceptable entry. \n";
       continue;
}
else{
     int y = x - '0';
}

int y = x - '0'看起来很奇怪;但是它在那里是因为您必须将char转换为int,然后根据ASCII编码,从所需的数字中减去字符“ 0”。您可以在这里看到:Convert char to int in C and C++

相关问题