Search code examples
cfilefgetsscanf

printing and scanning files in c


I'm writing a program in c with a file of names and numbers. the user inputs a number and then it should print out the name beside it. the file looks something like this...

154 Sam
245 Jane
345 Joe

Im not sure how to only print certain words from the file after matching the input from the user, but i do know when i use fgets and fscanf it printd the whole file

so far i have

FILE *pf;
pf = fopen("C:\\Sample.text", "a+");
char str[200];
char input2[10];
printf("\nPlease enter a number:");
scanf("%s", &input2);`

while(!feof(pf))
{
    fscanf(pf,"%s/n",str);

    if (strcmp(str,input2)==0)
    {
        printf("The First name is %s\n",fgets(str,10,pf));
    }
}

Solution

  • There are a number of ways to break up a line into parts so you can treat them individually, but since you're already using scanf and fscanf you might want to consider sscanf. Suppose you've read a whole line from the file into str, and the line contains both a number and a name:

    sscanf(str, "%s %s", number_str, name_str);
    

    would read the first word on the line into number_str and the second word on the line into name_str.