如何让 scanf 循环在到达文件末尾时终止?

How to get a scanf loop to terminate when it reaches the end of file?

我正在尝试阅读以白色分隔的单词 space。有未知数量的单词,会有多行输入。我想一次读两个单词,然后在继续之前比较它们。

现在读取和比较工作正常,但我还没有找到一种方法让循环在到达文件末尾并继续提示新输入时退出。

int main() {

char entry1[256];
char entry2[256];

printf("Enter some test words: \n");

while(scanf("%257[^ \t\n]%*c", entry1)){
    printf("compare 1: %s \n", entry1);

    scanf("%257[^ \t\n]%*c", entry2);
    printf("compare 2: %s \n", entry2);

    if ((anagramCheck(entry1, entry2)) == 1) 
        printf("\nThese two words are anagrams.\n");
    else
        printf("\nThese two words are not anagrams.\n");
}
}

这就是我想要实现的目标:

示例输入可能是:

table george creative reactive tabloid pipe

输出将是:

compare 1: table
compare 2: george

These two words are not anagrams.

compare 1: creative
compare 2: reactive

These two words are anagrams.

compare 1: tabloid
compare 2: pipe

These two words are not anagrams.

注意: -我正在用c89编译。 -我没有包括 anagramCheck,因为我认为它与我的问题无关。但如果碰巧我可以编辑和包含它。

通常的成语是

while (scanf("%255s%255s", entry1, entry") == 2) {
  printf("Compare 1: %s\nCompare 2: %s\n", entry1, entry");
  // ...
}

当它无法读取两个单词时将停止。我不清楚您希望使用 %s 无法完成的更复杂的 scanf 模式来完成什么。 (我将您的 257 更改为 255,因为这是您可以容纳在 256 字节字符数组中的最大字符数。)

请注意 scanf returns EOF (通常为 -1)出错,就 C 而言,这是一个真实值。使用 while (scanf(...)) { ... } 几乎不是一个好主意,因为这会导致循环在错误或文件结束时继续。

来自 Linux 系统上的 man scanf

These functions return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.

The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs. EOF is also returned if a read error occurs, in which case the error indicator for the stream is set, and errno is set indicate the error.