首页 > 解决方案 > 检查输入是否根本不是整数或数字 cpp

问题描述

我创建了一个猜谜游戏,您必须在 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;
}

标签: c++integerinfinite-loopcin

解决方案


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

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

编辑:我应该说,在研究了这个之后,我意识到isdigit要工作,条目需要是一个字符。但是,如果在发现它是 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++


推荐阅读