0

Im trying to make a program that lets the user search for stored names in an array.

Using the documentation for C, this is the code I have so far.

The problem here however, is that when I run the program, it allways prints "No match found".

Which leads me to the conclusion that something may be wrong.

Can someone point me in the right direction, or simply explain what I have done wrong here?

Quite frankly, any sugguestions on improvements are welcome (for learning purposes).

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



int main(){


        char src[10];

        char names[][10] = {"Daniel", "Thomas", "Katty", "Chris", "Mary", "Otto"};

        printf("Seach for a name: ");
        fgets(src, 10, stdin);

        for(int i = 0; i < 7; i++){

                if(strcmp(names[i], src)==0){

                        printf("Found a match!\n");
                        return 0;
                }


        }
        printf("No match was found!\n");
        return 1;
}
MCmcoy
  • 11
  • 4
  • 2
    `fgets()` leaves the newline at the end of the string. Since none of the names end with newline, they won't match. – Barmar Jul 29 '22 at 19:37
  • Thanks! I tried putting "\n" behind the names and that worked. However, that seems like a tedious and an ineffective way to correct the list of names. Is there a better way to get the input (other then fgets) or a way to avoid the newline? – MCmcoy Jul 29 '22 at 19:47
  • Read the linked question. It shows how to remove the `\n`. – Barmar Jul 29 '22 at 19:48

0 Answers0