I am attempting to create a program that allows me to search for a name in a text file. At this point the program will successfully tell me whether or not the name is on the roster, but it will also print every other line as well! For example, if I am looking to see if "Sarah" will be on the roster, it will say
Sarah is not on the roster
Sarah is number 7 on the roster
Sarah is not on the roster
I simply want it to tell me if "Sarah" is on the roster or not. I'm very, very new to teaching myself C, so I'm assuming I'm doing something stupid.
#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;
}
You need to keep track of whether the name
was found, and only print the "not on the roster" message if you finish the while
loop without finding the name.
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);