C语言中的scanf

Scanf in C programming

如何使用 scanf 获取字符而不是数字。

示例: 输入:“2827h829k90157” 输出:“h k”

请不要使用 for,while 和 if else。

输入说明符 %d 读取数字并在非数字字符处停止。

添加 *%*d 读取 %d 之类的数字并将其删除,而不是存储到通过参数指定的位置。

因此输入输出对可以通过:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char c1, c2;
    scanf("%*d%c%*d%c", &c1, &c2) == 2 || (exit(1), 0);
    printf("%c %c\n", c1, c2);
    return 0;
}

demo

禁止使用if,所以我使用了||运算符的短路求值来做输入检查,读取失败时退出。

exit()的return类型是void,不能和||运算符一起使用,所以我加了, 0来解决这个问题。