c - 在 C 中显示正确的 bool 值

标签 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 中的字符串操作的更多信息。每当我运行此代码时,除非我将字母或符号传递到 check_num,否则程序会输出“0”而不是像我希望的那样输出“1”。这是怎么回事?

最佳答案

应该是

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

关于c - 在 C 中显示正确的 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37466748/

相关文章:

c - 使用 fscanf 读取文本文件未按预期工作

c - 如何优化反转位组的顺序

C++ 字符串 "insert"函数在多次运行时使应用程序崩溃

c# - C# 是否有一些函数可以用表单输入字符串?

二维字符串数组的 C 内存布局

javascript - JS 中的正则表达式

c - 嵌套结构和 Typedef

c - 如何让Sublime Text 3执行编写的程序?

c - 如何使用 gcc 运行(和编译)带参数的 C 文件?

java - 排序多个数组列表的数组列表