在C中显示适当的布尔值

时间:2016-05-26 16:47:05

标签: c string

 //This program determines if a string is made up entirely of numbers.
 //It should output 1 if the string only consists of numbers and either
 //output 0 or nothing at all if otherwise. 
 #include <stdio.h>
 #include <stdbool.h>

 bool check_num(const char *str) {
     for (int i = 0; str[i] != '\0'; ++i){ //Iterating through
         if (str[i] < '0' || str[i] > '0'){
             return false;  //Is this return statement correct?
         }
     }

     return true;
 }

 int main() {
     bool a = check_num("1");
     printf("%d\n", a);

     return 0;
 }

我正在尝试更多地了解C中的字符串操作。每当我运行此代码时,程序输出'0'而不是像我想要的那样输出'1',除非我将字母或符号传递给check_num。这是怎么回事?

1 个答案:

答案 0 :(得分:1)

那应该是

if (str[i] < '0' || str[i] > '9') {
//                            ^