在c中如何判断一个char是否是一个数字?

agu*_*450 -1 c char atof

我正在使用atof(word),其中单词是一种char类型。当单词是数字(例如 3 或 2)时它起作用,但 atof 不区分单词是运算符(例如 )"+"。有没有更好的方法来检查字符是否是数字?

我是 CS 的新手,所以我对如何正确执行此操作感到很困惑。

dbu*_*ush 5

如果您要检查单个char,请使用该isdigit函数。

#include <stdio.h>
#include <ctype.h>

int main()
{
    printf("2 is digit: %s\n", isdigit('2') ? "yes" : "no");
    printf("+ is digit: %s\n", isdigit('+') ? "yes" : "no");
    printf("a is digit: %s\n", isdigit('a') ? "yes" : "no");
}
Run Code Online (Sandbox Code Playgroud)

输出:

2 is digit: yes
+ is digit: no
a is digit: no
Run Code Online (Sandbox Code Playgroud)