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

Check if input is not integer or number at all cpp

本文关键字:整数 数字 输入 是否 检查      更新时间:2023-10-16

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

对于一个解决方案,您可以尝试使用isdigit。这将检查输入是否实际上是一个数字。所以你可以做一些类似的事情:

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

编辑:我应该说,在研究了这个之后,我意识到isdigit要工作,条目必须是一个字符。然而,如果您在发现char是int之后将其转换为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"。您可以在这里看到:在C和C++中将char转换为int