【问题标题】:How to limit scanf while reading input from file从文件读取输入时如何限制scanf
【发布时间】:2019-07-03 08:08:14
【问题描述】:

我是 C 初学者,我编写了一个类似的程序:

#include<stdio.h>

int main() {

    char r[10];
    char y[10];
    puts("Printing Data \n");
    while (scanf(" %10s %s",r,y) == 2) {
        printf("%s and %s\n",r,y);
}
    return 0;
}

CMD ./prog.c

文件.txt

aman dhaker
rudra pratap hensome
nitesh dhakar

虽然我希望 scanf 仅读取 2 个字符串,但在 file.txt 的第 2 行有 3 个字符串,但我想跳过第三个 arg,因为我只想打印 2 个字符串,但不知何故我无法跳过特定的字符串。

我目前的输出:

aman dhaker
rudra pratap hensome
nitesh dhakar

我想要的输出:

aman dhaker
rudra pratap
nitesh dhakar

请帮帮我。

我已经尝试包含像 [^] 这样的正则表达式来排除包含空格的结果,但没有成功。

【问题讨论】:

  • 攻击者九,如果一行输入只有"aman\n"会怎样?

标签: c


【解决方案1】:

您可以使用fgets 读取每一行,然后将sscanf 应用于读取的字符串,如下所示

#include <stdio.h>

int main(void) {

    char r[10];
    char y[10];
    char input[100];
    while(fgets(input, sizeof input, stdin) != NULL) {
        if(sscanf(input, "%9s%9s", r, y) == 2) {
            printf("%s %s\n", r, y);
        }
    }
    return 0;
}

程序输出:

阿曼达克 鲁德拉普拉塔普 尼特什达喀尔

请注意,我将字符串长度限制为 9 以允许使用 NUL 终止符。

使用fgets 然后sscanf 通常比使用scanf 更好。它使流控制更加容易,并且避免了清理输入缓冲区 - 如果输入错误,您可以忘记字符串并输入另一个。

【讨论】:

    【解决方案2】:

    即使您在 scanf 调用中指定只需要 2 个字符串,当您传递 3 个字符串时,另一个字符串仍保留在缓冲区中,您需要刷新/使用它:

    while (scanf("%9s %9s", r, y) == 2) { // No need to use a space before first %10s
        int c;                            // and you need space for the NUL terminator
        while ((c = fgetc(stdin)) != '\n' && c != EOF);
        printf("%s and %s\n", r, y);
    }
    

    【讨论】:

    • 第二个“%10s”之前也不需要空格。
    • @chux,对,但是 IMO 这更清楚地表明您正在扫描两个字符串
    猜你喜欢
    • 1970-01-01
    • 2018-02-15
    • 1970-01-01
    • 2015-04-02
    • 2011-07-18
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    相关资源
    最近更新 更多