检查数组是否只包含数字

时间:2013-12-01 13:09:11

标签: c arrays

我遇到问题,我想要通过一个数组并检查是否只输入了正数。我知道可以使用ctype.h中的isDigit,但我宁愿自己构建一些东西。我认为可行的方法是迭代遍历数组的每个元素,看看存储在那里的值是否在0到9之间,但它不起作用。到目前为止,这是我的代码:

char testArray[11] = {'0'};  
printf("Enter a string no longer than 10 chars");  
scanf("%s", testArray);  
int x;  
int notanumber = 0;  
for (x = 0; x < 11; x++) {  
        if ((testArray[x] < 0) || (testArray[x] > 9)) {  
                notanumber++;  
        }  
}  
printf("%i", notanumber);

2 个答案:

答案 0 :(得分:1)

它不起作用,因为09是整数而不是字符。 将您的if条件更改为

if((testArray[x] >= '0') || (testArray[x] <= '9')){ ... }   

检查0到9之间的数字。

答案 1 :(得分:0)

这一行

if((testArray[x] < 0) || (testArray[x] > 9)){  

应替换为

if((testArray[x] < '0') || (testArray[x] > '9')){  
相关问题