Home > Blockchain >  Is my strcmp usage incorrect in this scenario?
Is my strcmp usage incorrect in this scenario?

Time:06-20

I'm creating a program where typing anything other than Small, small, Large, large will re-prompt the user for input but what happens is that it only accepts "Large" but not the other correct inputs. output

#include <stdio.h>
#include <string.h>
int main()
{
    char drinksize[5];
    do
        {
            printf("\nEnter Drink Size (Small or Large): ");
            scanf("%s", drinksize);
            if(strcmp(drinksize, "Small") == 1 || strcmp(drinksize, "small") == 1 || strcmp(drinksize, "Large") == 1 || strcmp(drinksize, "large") == 1)
            {
                printf("Incorrect item number! Please try again.");
            }
        }
        while (strcmp(drinksize, "Small") == 1 || strcmp(drinksize, "small") == 1 || strcmp(drinksize, "Large") == 1 || strcmp(drinksize, "large") == 1);
}

CodePudding user response:

Yes.

Quoting from spec (e.g. https://en.cppreference.com/w/c/string/byte/strcmp ):

Return value Negative value if lhs appears before rhs in lexicographical order.
Zero if lhs and rhs compare equal.
Positive value if lhs appears after rhs in lexicographical order.

It does not say "1" anywhere and I suspect you want 0 for this.

Also your scanf() is risky, vulnerable to attacks and even incorrect for exactly the inputs you expect. You need more buffer even for predicted inputs like "Small" or "small".

  •  Tags:  
  • c
  • Related