Search code examples
carraysstrcmptoupper

Converting strings to uppercase to compare with user input in C


I am attempting to create a program that will allow a user to search for a name in a file. The program does this successfully, but then it occurred to me that not everyone will type in the name as it is capitalized in the file. That is, someone may search for "sarah," but as the name is listed as "Sarah" in the file the name will not be found. To get around this I have attempted to convert both strings into upper case at the time of comparison. I am very, very new to teaching myself C, so I am not certain if I am even heading in the right direction. At this point I cannot even get the program to compile as I am getting two errors that say "array initializer must be an initializer list or string literal." I'm assuming that to mean that my syntax is not only invalid but completely in the wrong direction. What would be the best way to approach my goal?

     #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], name[20];

        printf("Enter a name: __");
        scanf("%s", name);
        int found = 0;
        while(fscanf(inFile, "%s %s %s", rank, bname, gname)== 3)
        {   char uppername[40] = toupper(name[15]);
            char upperbname[40] = toupper(bname[15]);
            if(strcmp(uppberbname,uppername) == 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);

        return 0;

      }

Solution

  • use the following function, which is included in strings.h

    int strcasecmp(const char *s1, const char *s2);
    

    in your case change if statement

    if(strcmp(uppberbname,uppername) == 0)
    

    to

    if(strcasecmp(bname,name) == 0)
    

    and delete

    char uppername[40] = toupper(name[15]);
    char upperbname[40] = toupper(bname[15]);