有没有办法检查用户输入是否是数字?

Is there a way I can check if user input is a number?

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

我做了一个用户需要猜数字的游戏,

该数字是使用rand函数生成的。

如果用户写入了无效的数字或字符,请打印错误消息。

我的问题是cin.fail()对我来说效果不佳,例如,当我输入一个字符作为输入时,我的程序总是打印"太低了!",也许是因为它计算字符的值(ASCII TALBE(。

有什么建议吗?

我的代码:

void Game()
{
srand(time(0));
int iGuess;
const unsigned int iNum = (rand() % 1000 + 1);
Start:
system("cls");
cout << "n Guess the Num: "; cin >> iGuess;
if (iGuess == iNum) {
system("color A");
cout << "nn Good Job! You Won!";
exit(0);
}
if (iGuess > iNum) {
cout << "nn Too High!";
Sleep(3000);
goto Start;
}
if (iGuess < iNum) {
cout << "nn Too Low!";
Sleep(3000);
goto Start;
}
if (cin.fail()) {
cout << "Input has failed! & Error Code: " << GetLastError();
Sleep(3000);
goto Start;
}
}

首先,您可以检查对于,布尔转换 (explicit operator bool() const( 等效于!failed()(见 https://en.cppreference.com/w/cpp/io/basic_ios/operator_bool(。

这允许您编写:

void Game()
{
srand(time(0));
int iGuess;
const unsigned int iNum = (rand() % 1000 + 1);
Start:
system("cls");
cout << "n Guess the Num: ";
if (cin >> iGuess)
{
if (iGuess == iNum)
{
system("color A");
cout << "nn Good Job! You Won!";
exit(0);
}
if (iGuess > iNum)
{
cout << "nn Too High!";
Sleep(3000);
goto Start;
}
if (iGuess < iNum)
{
cout << "nn Too Low!";
Sleep(3000);
goto Start;
}
}
else
{
cin.clear();                        // clear error flags
cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n'); // empty buffer 
assert(cin);                        // check that we are still in a good state
cout << "Input has failed! & Error Code: " << GetLastError();
Sleep(3000);
goto Start;
}
}

如果发生错误,请务必不要忘记以下步骤:

清除错误标志:

cin.clear(); 

删除以前存储在缓冲区中的所有数据(并且无法解释为整数(

cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n'); 

检查我们是否仍然处于良好状态(防御性编程,可能发生了另一个错误(

assert(cin); 

更新: 使用ignore当然更好,我的第一个版本是

while (cin.get() != 'n') continue; 

我的更新是:

cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n'); 

使用std::string_viewstd::isdigit()解析输入字符串的最简单方法。

char str[] = "12abc12"; 
int alphabet = 0, number = 0, i; 
for (i=0; str[i]!= ''; i++) 
{ 
// check for alphabets 
if (isalpha(str[i]) != 0) 
alphabet++; 
// check for decimal digits 
else if (isdigit(str[i]) != 0) 
number++; 
} 

https://www.geeksforgeeks.org/isalpha-isdigit-functions-c-example/

我建议使用 do while 格式来获取您的输入。

#include <stdlib.h>
#include <time.h>
#include <iostream>
#ifdef _WIN32
#include <windows.h>
void sleep(unsigned milliseconds)
{
Sleep(milliseconds);
}
#else
#include <unistd.h>
void sleep(unsigned milliseconds)
{
usleep(milliseconds * 1000); // takes microseconds
}
#endif
using namespace std;
int main()
{
srand(time(0));
int iGuess;
const unsigned int iNum = (rand() % 1000 + 1);
Start:
system("cls");
do
{       
if (!std::cin)
{
std::cin.clear();
std::cin.ignore(10000, 'n');
std::cout << "nFailed input";
}
std::cout << "n Guess the Num: ";
} while (!(std::cin >> iGuess));

if (iGuess == iNum) {
system("color A");
cout << "nn Good Job! You Won!";
exit(0);
}
if (iGuess > iNum) {
cout << "nn Too High!";
Sleep(3000);
goto Start;
}
if (iGuess < iNum) {
cout << "nn Too Low!";
Sleep(3000);
goto Start;
}
}