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

标签 c macos scanf strcmp

我正在尝试创建一个允许我在文本文件中搜索名称的程序。此时程序会成功地告诉我这个名字是否在名册上,但它也会每隔一行打印一次!例如,如果我要查看“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;
}

最佳答案

您需要跟踪姓名是否被找到,并且只在完成后打印“不在名册上”消息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);

关于c - 从文件中搜索和打印字符串时,打印的是每一行,而不是我需要的那一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36702716/

相关文章:

c - 在类型转换为不同类型后访问数组时出现段错误

c++ - 检查字符串是否以 (%i) 结尾,然后将该数字分配给变量

c - 在 C 中帮助 While 循环

objective-c - 接受 iPhoto 或 Aperture 的拖放

c - C 练习文件中的 Fscanf

Calloc() 不分配零

c - C 中的 system() 函数

c - __attribute__ 是否适用于声明中的所有变量?

c - 为什么 cross gcc 调用 native 'as' ?

macos - Microsoft Azure 存储资源管理器不加载本地模拟器存储