1

我是 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

文件.txt

aman dhaker
rudra pratap hensome
nitesh dhakar

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

我当前的输出:

aman dhaker
rudra pratap hensome
nitesh dhakar

我想要的输出:

aman dhaker
rudra pratap
nitesh dhakar

请帮帮我。

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

4

2 回答 2

5

您可以使用 读取每一行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终止符。

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

于 2019-07-03T08:21:31.647 回答
3

即使您指定在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);
}
于 2019-07-03T08:20:20.543 回答