如何判断字符串为数字c语言
时间: 2023-11-15 15:01:31 浏览: 103
在C语言中,可以使用标准库函数`isdigit()`来判断一个字符是否为数字。如果要判断一个字符串是否为数字,可以遍历字符串中的每个字符,逐个判断是否为数字。以下是一个示例代码:
```c
#include <stdio.h>
#include <ctype.h>
int is_number(char *str) {
int i = 0;
while (str[i]) {
if (!isdigit(str[i])) {
return 0;
}
i++;
}
return 1;
}
int main() {
char str1[] = "12345";
char str2[] = "12a45";
if (is_number(str1)) {
printf("%s is a number\n", str1);
} else {
printf("%s is not a number\n", str1);
}
if (is_number(str2)) {
printf("%s is a number\n", str2);
} else {
printf("%s is not a number\n", str2);
}
return 0;
}
```
输出结果为:
```
12345 is a number
12a45 is not a number
```