【问题标题】:How to make scanf stop reading from input based on the first char?如何使scanf根据第一个字符停止从输入中读取?
【发布时间】:2021-12-10 08:16:17
【问题描述】:

我被scanf()困住了 有人可以帮助我并告诉我如何阅读scanf() 中的第一个字符,并根据该字符决定我是否要阅读 1 个或 2 个或 3 个输入: 例如 : scanf( char , int int int) 如果字符 S,输入后如何让它停止:

S 45

【问题讨论】:

  • 使用多个scanf,第一个scanf只读取1个字符,后续scanf根据读取的字符选择读取多少个整数。

标签: c scanf


【解决方案1】:

对于这类问题,一般来说为了更容易进行错误恢复,您应该使用fgets() 一次读取一行输入,然后使用sscanf() 解析该行。

这是一个例子:

#include <stdio.h>

int main() {
    char line[128];
    printf("Enter letter and values:\n");
    if (fgets(line, sizeof line, stdin)) {
        if (*line == 'A') {
            int a, b, c;
            if (sscanf(line, "A %d %d %d", &a, &b, &c) == 3) {
                printf("A code, a=%d, b=%d, c=%d\n", a, b, c);
            } else {
                printf("A code requires 3 integers\n");
            }
        } else
        if (*line == 'S') {
            int a;
            if (sscanf(line, "S %d", &a) == 1) {
                printf("S code, a=%d\n", a);
            } else {
                printf("S code requires 1 integer\n");
            }
        } else
        {
            /* handle other input codes... */
        }
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多