[英]Having some problems with strcmp() - code compiles but doesn't seem to work
我试图让用户给我一个运算符(+,-,/,*)。 为了确保他/她做到这一点,我编写了以下代码:
#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));
}
最终会发生的是,即使我输入了正确的运算符,循环仍在继续。 任何帮助表示赞赏。 谢谢 :)
编辑:(固定代码)
#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));
}
strcmp
函数采用以零结尾的字符串,而不是字符。 因此,使用
strcmp(&operator, "+")
是导致未定义行为的原因。
您的代码可能很简单
while ((operator != '+') && ...)
注意,我也更改了||
到&&
。
您还需要在"%c"
之前加一个空格,例如" %c"
这样,如果重复输入循环,它将清除输入缓冲区中剩余的所有newline
。
编辑:您似乎没有做出正确的更正,我建议
do {
scanf(" %c", &operator);
} while (operator != '+' && operator != '-' && operator != '*' && operator != '/');
通过以下方式声明变量运算符
char operator[2] = { '\0' };
并像这样使用
do { scanf("%c ", operator); }
while ((strcmp( operator, "+") != 0) && (strcmp(operator, "-") != 0) && (strcmp(operator, "*") != 0) && (strcmp(operator, "/") != 0));
}
考虑到可以使用一个函数strchr
而不是使用大量的strcmp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.