Search code examples
cstringcomparison

String comparison in C with operators


I can't compare between operators and it takes 1 only input and then the program crashes.

char operatorValue;
do
{

    printf("\nEnter Operator:");
    scanf("%c", &operatorValue);

} while (strcmp(operatorValue, '+') != 0 || strcmp(operatorValue, '-') != 0 ||
         strcmp(operatorValue, '*') != 0 || strcmp(operatorValue, '/') != 0);

Solution

  • It may be easier to use the strchr function, defined as

    char *strchr(const char *string, int c);
    

    It finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search. Returns NULL if the character is not found. See the following page for a full description and example of use

    https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_71/rtref/strchr.htm

    char target = "+-*/";
    ....
    } while  (strchr(target, (int) operatorValue)) ==0); // loops until it gets a match
    

    Then if you want to add more characters to the search string it is easy.