Search code examples
cstringcharacterstrcmp

Having some problems with strcmp() - code compiles but doesn't seem to work


I'm trying to get the user to give me an operator (either +,-,/,*). In order to ensure he/she does this, I wrote this code:

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



int main(void)
{
char operator;

printf("Enter operator: (+, -, *, /) \n");

do { scanf("%c", &operator); }
while ((strcmp(&operator, "+") != 0) || (strcmp(&operator, "-") != 0) || (strcmp(&operator, "*") != 0) || (strcmp(&operator, "/") != 0));
}

What ends up happening is the loop goes on and on, even if I enter the correct operator. Any help is appreciated. Thanks :)

Edit: (Fixed code)

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



int main(void)
{
char operator;

printf("Enter operator: (+, -, *, /) \n");

    do { scanf(" %c", &operator); }
 while ((strcmp(&operator, "+") != 0) && (strcmp(&operator, "-") != 0) && (strcmp(&operator, "*") != 0) && (strcmp(&operator, "/") != 0));

}

Solution

  • The function strcmp takes a zero-terminated string, not a character. For that reason, use of

    strcmp(&operator, "+")
    

    is cause for undefined behavior.

    Your code could be as simple as

    while ((operator != '+') && ...) 
    

    Notice I also changed the || to &&.

    You also will need a space before "%c" like this " %c" so that if the input loop repeats, it clears off any newline that was left in the input buffer.

    EDIT: You don't seem to have made the right correction, I suggest

    do {
        scanf(" %c", &operator);
    } while (operator != '+' && operator != '-' && operator != '*' && operator != '/');