c - 如何使用 C 中的 bool 函数确定用户输入是否为数字

标签 c integer character

我想弄清楚如何使用 bool 函数确定用户输入的是数字而不是 C 中的字母/符号 (A,a,!,@,#,$,%)。我使用的代码(if 语句)仅适用于小写和大写字母。下面是我的 if 语句代码。下面我将包括我正在(未成功)尝试的 bool 函数。我的 bool 函数中是否遗漏了什么?

    if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
    printf("Character '%c' does not represent a digit\n", ch);}


    _Bool isNumber(char ch) {
    printf("Character '%c' does not represent a digit\n", ch);
    return 0;}

没有库函数可以吗?

最佳答案

C 标准库已经了这样一个野兽:

#include <ctype.h>
:
if (! isdigit(ch)) {
    printf("'%c' is not a digit\n", ch);
}

如果由于某些奇怪的原因(a)您不能使用标准库函数,只需自己动手:

bool isDigit(int ch) {              // Uppercase D to distinguish it.
    return ch >= '0' && ch <= '9';
}

您也可以直接在代码中而不是作为一个函数来完成:

if (ch <  '0' || ch >  '9') puts("Not a digit"); // or:
if (ch >= '0' && ch <= '9') puts("Is  a digit");

标准保证 C 中的数字字符是连续的,这与所有其他字符不同。这就是为什么对 alpha(如 ch >= 'a' && ch <= 'z' )做同样的事情是个坏主意。

请记住,单个 字符是数字。这似乎是你想要的。要检查一个字符 string 是否是一个有效的整数,它需要更复杂。基本上,每个字符都需要是一个数字,并且它的前面可能有一个可选的符号。像这样的事情将是一个好的开始:

bool isInt(char *sstr) {
    unsigned char *str = sstr;
    if (*str == '+' || *str == '-')
        ++str;
    if (! isdigit(*str++))          // or your own isDigit if desired.
        return false;
    while (*str != '\0')
        if (! isdigit(*str++))      // ditto.
            return false;
    return true;
}

(a) 虽然我想您可能想出于教育目的这样做,但不一定奇怪:-)

关于c - 如何使用 C 中的 bool 函数确定用户输入是否为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56096697/

相关文章:

c++ - 分配后如何用字符串填充字符?

java - Integer.parseInt 不将字符串解析为整数

php - 范围内均匀分布的整数

c - 如何读取空格分隔的整数序列,直到遇到换行符?

c - C 语言的翻译限制

c - 通过 OpenGL 进行图形编程,无需 Windows 编程

c - 关于C中字符串的问题

c - 为什么 C 数组初始化语法不允许任意赋值?

C 中的 `restrict` 限定符可以帮助查找由于重叠 block 而导致的错误吗?

c - 将字符串结尾字符添加到文件会损坏它..?