Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is my strcmp usage incorrect in this scenario?

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);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading