读书人

如何判断键盘输入的是不是整型数据

发布时间: 2012-11-03 10:57:44 作者: rapoo

怎么判断键盘输入的是不是整型数据?
如标题。求解答。

[解决办法]

C/C++ code
[User:root Time:23:25:40 Path:/home/liangdong/c]$ ./output 123123 is a number456456 is a number123 a123 a is not a number123a123a is not a number0 is a numbersdfsdf is not a number^C[User:root Time:23:26:04 Path:/home/liangdong/c]$ cat src/main.c #include <stdio.h>#include <stdlib.h>#include <string.h>int is_int(const char *str) {        if (!str) {                return -1;        }        int len = strlen(str);        int i = 0;        for ( ; i != len; ++ i) {                if (!isdigit(str[i])) {                        return 0;                }        }        return 1;}int main(int argc, char* const argv[]) {        char input[100];        while (fgets(input, 100, stdin) != NULL) {                int len = strlen(input);                if (input[len - 1] == '\n') {                        input[len - 1] = '\0';                }                if (is_int(input) == 1) {                        printf("%d is a number\n", atoi(input));                } else {                        printf("%s is not a number\n", input);                }        }        return 0;}
[解决办法]
探讨

C/C++ code
[User:root Time:23:25:40 Path:/home/liangdong/c]$ ./output
123
123 is a number
456
456 is a number
123 a
123 a is not a number
123a
123a is not a number

0 is a number
sdf
sdf is not a n……

[解决办法]
探讨

C/C++ code
[User:root Time:23:25:40 Path:/home/liangdong/c]$ ./output
123
123 is a number
456
456 is a number
123 a
123 a is not a number
123a
123a is not a number

0 is a number
sdf
sdf is not a n……

[解决办法]
探讨

3楼的不行啊,输入实型的时候scanf的返回值也是1

读书人网 >C语言

热点推荐