【问题标题】:Having some problems with strcmp() - code compiles but doesn't seem to workstrcmp() 有一些问题 - 代码编译但似乎不起作用
【发布时间】: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

标签: c string character strcmp


【解决方案1】:

函数strcmp 接受一个以零结尾的字符串,而不是一个字符。因此,使用

strcmp(&operator, "+")

是未定义行为的原因。

你的代码可以很简单

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

请注意,我还将 || 更改为 &amp;&amp;

"%c" 之前还需要一个空格,例如 " %c",这样如果输入循环重复,它会清除输入缓冲区中留下的任何 newline

编辑:我建议您似乎没有做出正确的更正

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

【讨论】:

  • 是的,这确实有效。为什么 && 起作用而不是 || ?
  • 因为使用|| 表示如果运算符不等于其中任何一个符号,则循环将重复,并且只能等于其中一个!
  • @ManuelStoilov 您编辑了您的问题,但不是解决方案 - 请参阅我的编辑。
【解决方案2】:

按如下方式声明变量运算符

char operator[2] = { '\0' };

并像使用它

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

考虑到你可以使用一个函数strchr,而不是使用多个strcmp

【讨论】:

  • 这会起作用,但它似乎几乎是故意混淆的。比较operator == '+' 更易读、更高效、更省事。 (您可以提到使用strchr 来与单个库函数进行所有比较。)
  • @rici Nothinh 阻止您使用 operator[0] == '+' 之类的比较。此外,我指出最好使用标准函数 strchr 而不是大量比较。我展示了如何正确使用 strcmp。
猜你喜欢
  • 1970-01-01
  • 2017-12-22
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 2018-07-05
  • 1970-01-01
相关资源
最近更新 更多