从文件中搜索和打印字符串时,打印的是每一行,而不是我需要的那一行

When searching and printing strings from a file, every line prints instead of the one I need

我正在尝试创建一个允许我在文本文件中搜索姓名的程序。此时程序会成功地告诉我这个名字是否在名册上,但它也会每隔一行打印一次!例如,如果我要查看 "Sarah" 是否会出现在名册上,它会显示

Sarah is not on the roster
Sarah is number 7 on the roster
Sarah is not on the roster

我只是想让它告诉我 "Sarah" 是否在名册上。我对自学 C 非常非常陌生,所以我假设我在做一些愚蠢的事情。

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main(void)
{
    FILE *inFile;
    inFile = fopen("workroster.txt", "r");
    char rank[4], gname[20], bname[20];
    char name[20];

    printf("Enter a name: __");
    scanf("%s", name);
    while(fscanf(inFile, "%s %s %s", rank, bname, gname)!= EOF)          
    {
        if(strcmp(gname,name) == 0)
            printf("%s is number %s on the roster\n", name, rank);
        else
            printf("%s is not on the roster\n", name);
    }
    fclose(inFile);

    return 0;
}

您需要跟踪 name 是否被 找到 ,并且只打印 "not on the roster"如果您完成 while 循环但未找到名称,则会收到消息。

int found = 0;
while(fscanf(inFile, "%s %s %s", rank, bname, gname)== 3)          
{
    if(strcmp(gname,name) == 0)
    {
        printf("%s is number %s on the roster\n", name, rank);
        found = 1;
    }
}

if ( !found )
    printf("%s is not on the roster\n", name);

您可以取一个 flag 并检查该名称是否存在。