【发布时间】:2016-07-12 16:20:12
【问题描述】:
我试图让用户给我一个运算符(+、-、/、*)。为了确保他/她这样做,我写了这段代码:
#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采用以零结尾的字符串,而不是字符。可以简单到if(operator == '+') -
@WeatherVane,您的评论值得转换为答案。
-
我认为我们还可以利用
char的内部表示是整数类型这一事实,因此可以简化比较以检查像这样的值operator != 42 -
@ImranAli 当您的意思是
'*'(int类型)时,请不要使用幻数。该符号不仅更易于阅读,而且无法保证它的数值为42。