我写了以下代码来检查输入(answer3)是一个数字还是字符串,如果它不是数字,应该返回"Enter Numbers Only",但即使是数字也返回相同的结果。请为我提供解决方案。
#include <iostream>
#include <string>
#include <typeinfo>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
using namespace std;
int main ()
{
string ques1= "Client's Name :";
string ques2 = "Client's Address :";
string ques3 = "Mobile Number :";
char answer1 [80];
string answer2;
int answer3;
cout<<ques1<<endl;
cin>>answer1;
cout<<ques2<<endl;
cin>>answer2;
cout<<ques3<<endl;
cin>>answer3;
if (isdigit(answer3))
{
cout<<"Correct"<<endl;
}
else
{
cout<<"Enter Numbers Only"<<endl;
}
system("pause>null");
return 0;
}
isdigit
函数接受一个单字符作为int
,将其解释为 ASCII 字符,并返回非零值,如果它是数字字符('0' 到 '9',ASCII 48 到 57),否则返回零。它无法告诉你是否将整数读入到answer3
中。 - Mike DeSimonecin >> someIntVariable
会忽略前导空格,读取一个可选符号 (-
或+
) ,后跟一串数字,直到第一个非数字字符。因此,如果有人输入不能被解释的内容,它会将变量设置为0。这就是为什么稍后的isdigit
会失败。 - Mike DeSimoneisdigit
没有任何意义。 - David Schwartz