C 检查值是否为十进制数字(不是作为字符的数字)

C 检查值是否为十进制数字(不是作为字符的数字),c,C,我想检查用户输入的值是否为整数(我指的是整数,而不是字符形式的数字(如char))。 我使用了isdigit函数,并且是…姐妹,但效果不好 例如: int digits = 220; // Or scanf("%d", digits); Or any way to take the input from user if(digits == `integer number`){ // do things }else{ // do things } 就这样。你完了 或者,如果scanf

我想检查用户输入的值是否为整数(我指的是整数,而不是字符形式的数字(如char))。
我使用了
isdigit
函数,并且
是…
姐妹,但效果不好

例如:

int digits = 220; // Or scanf("%d", digits); Or any way to take the input from user
if(digits == `integer number`){
   // do things
}else{
   // do things
}
就这样。你完了

或者,如果
scanf(“%d”,&digits)
返回
1
,则整数已成功读取并以数字形式存储

注意声明
int digits
确保只能在
digits
中存储整数值

因此:


我使用了isdigit函数,并且是。。。姐妹们,但效果不好。
?@Acme:我使用了
int-isdigit(int-c)
,但效果不好。如果您使用
%d
修饰符执行
scanf
,并向其发送指向
int
的指针,则您不能拥有任何非十进制数的东西@Nathan Fellman:谢谢,但是我不关心从用户那里获取输入的方法,我关心的是检查用户输入是整数还是否。是否
scanf
返回读取的字符数?在这种情况下,您应该检查
!=0而不是
==1
@Klas Lindbäck:很好,你是对的。但这取决于我们是否使用
scanf
。因此,如果我们使用其他方式从用户处获取输入?@Lion King:无论您如何写入
int
类型化变量,它始终是
int
@Nathan返回值是读取的值/令牌数。当用户输入诸如“3.5”之类的内容时,此方法返回错误地指示true。在这种情况下,
scanf
读取“3”,将其分配给(通过指针)传递给它的
int
,并在“.”处停止,而不指示错误。
int digits = 220; // Or scanf("%d", &digits);
int digits;

if (scanf("%d", &digits) == 1) {
  // Integer was read successfully from stdin and assigned to digits
} else {
  // Integer was not read. No value was assigned to digits
}