c - 我将如何编写只接受某些字符的 scanf() 语句?

标签 c logic boolean-logic

对于我正在编写的程序,我需要使用 scanf() 仅扫描 0-9、A-Z 和 a-z 之间的字符。

我想我可以使用一些不错的比较运算符来帮助我实现我的目标。例如,也许这可行:

int i = 3;
char a[7] = {'a', 'b', 'c', '?', 'e', 'f', '\0'};

if (!(a[i] >= '0' && a[i] <= '9') && !(a[i] >= 'A' && a[i] <= 'Z') && !(a[i] >= 'a' && a[i] <= 'z'))
  printf("not 0-9. A-Z, or a-z!\n");

换句话说,如果a[i]中的字符不是数字或字母,则打印语句。但是,那没有用。还有其他选择吗?

最佳答案

C 标准库提供了测试字符为 digit 的函数或 letter :

if (!isalpha(a[i]) && !isdigit(a[i])) {
    printf("Not a letter or a digit\n");
}

您需要包括 <ctype.h>以便引用这些函数。

关于c - 我将如何编写只接受某些字符的 scanf() 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34235408/

相关文章:

c++ - C/C++ 中大数组的运行时错误

logic - 如何在 Agda 中证明 `theorem : ¬ ⊤ ≡ ⊥`?

scheme - 你如何在 Scheme 中表达 bool 否定?

logic - P暗示Q,英文怎么读

c - 程序可以工作,但最终检测到**堆栈粉碎**

c - 我无法将 char 字符串分配给 char 数组

c - Linux : what prevents us from reading the memory from code segment?

mysql在where子句中使用逻辑+组函数的无效使用

logic - Agda 中的排中律

java - 编码Bat : LoneSum optimization