Search code examples
cwhile-loopstrcmp

strcmp not working in while loop


What I want to do in my C code is to check for user input and validate that they can only type in either "one" or "two". I made a while loop that checks the user input value with strcmp, but it does not work. The while loop seem to be ignoring the getchar(); and going on an infinite loop.

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

     int main ()
       {
        char choice[80];
        while(strcmp (choice,"one") != 0 || strcmp (choice,"two") != 0){
        scanf("%s", &choice);
        getchar();
        }
        // if the user enters either one or two, continue executing code...
       return 0;
     }

Solution

  • I saw 3 issues in your code:

    1

    while(strcmp (choice,"one") != 0 || strcmp (choice,"two") != 0)
    

    This condition never evaluates to false. Because either the user enters one or two or aything else the any of the or both strcmp condition returns true.

    2

     scanf("%s", &choice);
    

    No need of & there. For reading string to an character array using %s you don't need to use & (because when you specify the name of character array the address is pointed).

    Just write like:

    scanf("%s", choice);
    

    3

    It's a logical one. You just declared an character array. And on the next line you are using it in strcmp. surely the array will have garbage values.

    My solution:

    Implement your code like:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main ()
    {
       char choice[80];
       while(1)
       {
            scanf("%s", choice);
            if(strcmp (choice,"one") == 0 || strcmp (choice,"two") == 0)
            {
               break;
            }
            getchar();
       }
       // if the user enters either one or two, continue executing code...
       return 0;
    }