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