我想弄清楚如何使用 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/