C与操作员的字符串比较



我无法在操作员之间进行比较,并且仅需要1个输入,然后程序崩溃。

char operatorValue;
do
{
    printf("nEnter Operator:");
    scanf("%c", &operatorValue);
} while (strcmp(operatorValue, '+') != 0 || strcmp(operatorValue, '-') != 0 ||
         strcmp(operatorValue, '*') != 0 || strcmp(operatorValue, '/') != 0);

运算符值是char。您不能使用i

使用字符串函数
    while (operatorValue != '+' ||  ....

使用 strchr 函数可能更容易,定义为

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

它发现字符串中字符的第一次出现。字符c可以是null字符( 0(;搜索中包含字符串的结尾空字符。如果找不到字符,则返回null。有关完整说明和使用示例,请参见下一页

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

然后,如果要在搜索字符串中添加更多字符,这很容易。

最新更新