C 判断一个字符串是否为整数
时间: 2023-08-22 09:04:26 浏览: 157
可以使用 C 标准库中的 `atoi()` 函数将字符串转换为整数,如果字符串不能被转换为整数,则返回 0。
示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int is_integer(char* str) {
int len = strlen(str);
if (len == 0) {
return 0;
}
int i = 0;
if (str[0] == '+' || str[0] == '-') {
i++;
}
for (; i < len; i++) {
if (!isdigit(str[i])) {
return 0;
}
}
return 1;
}
int main() {
char str1[] = "123";
char str2[] = "+456";
char str3[] = "-789";
char str4[] = "12.3";
char str5[] = "abc";
printf("%s is %sinteger\n", str1, is_integer(str1) ? "" : "not ");
printf("%s is %sinteger\n", str2, is_integer(str2) ? "" : "not ");
printf("%s is %sinteger\n", str3, is_integer(str3) ? "" : "not ");
printf("%s is %sinteger\n", str4, is_integer(str4) ? "" : "not ");
printf("%s is %sinteger\n", str5, is_integer(str5) ? "" : "not ");
return 0;
}
```
输出结果:
```
123 is integer
+456 is integer
-789 is integer
12.3 is not integer
abc is not integer
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)