-3

我有一个 strcmp 函数:

if (strcmp(userInput, "Yes") == 0)

由于某种原因,它不会进入 if 语句,即使我确信用户输入肯定等于 Yes。任何人都知道有什么问题吗?

4

4 回答 4

3
  1. 确保您包含正确的标题,即<string.h>.
  2. 如果您userInput来自 eg fgets(),请确保最后没有行终止,它会干扰这样编写的比较。
于 2012-12-11T18:33:50.647 回答
2

为避免出现拖尾换行的麻烦,您可以只检查前 3 个字符:

if(strncmp(userInput, "Yes", 3) == 0)
于 2012-12-11T18:31:36.840 回答
1

照原样,您的代码很好。那不是问题。

我怀疑你正在这样做:

fgets(userInput, sizeof(userInput), stdin);
if(strcmp(userInput, "Yes") == 0)

这给了你一个换行符:

['Y']['e']['s']['\n']

您可以通过多种方式解决此问题:

if(strcmp(userInput, "Yes\n") == 0)

应该是最简单的了。或者你可以通过 scaf 获得输入:

scanf("%s", userInput);
于 2012-12-11T18:36:28.333 回答
0

如果需要帮助,可以进行类型转换。

//I am assuming usrInput is a char Array

string str(usrInput);
//string class has a constructor that takes a NULL-terminated C-string
if (str == "Yes")
{
   //do what ever you wanted to in the loop
}
于 2012-12-11T18:54:21.023 回答