简体   繁体   English

问题strcmp()无法正确比较字符串

[英]issue with strcmp() not comparing strings properly

Here's the actual code, since it seems to be specific to something here. 这是实际的代码,因为它似乎特定于此处的内容。

#include <iostream>
#include <string.h>

using namespace std;

int main()

cout << "  Just say \"Ready\" when you want to start.";
char tempReady[20];
cin >> tempReady;
length = strlen(tempReady);
char* ready = new char[length+1];
strcpy(ready, tempReady);
while((strcmp(ready, "Ready")||strcmp(ready, "ready"))!=0)
   {
   cout << "Try again.";
   cin >> tempReady;
   length = strlen(tempReady);
   delete[] ready;
   ready = new char[length+1];
   strcpy(ready, tempReady);
   }
cout << "Success";

Anyone see anything wrong? 有人看错吗?

C-style approach: C风格的方法:

char str[256];
if (scanf("%255s", str) == 1 && strcmp(str, "hello") == 0) {
    printf("success");
}

C++ approach: C ++方法:

std::string str;
if (std::cin >> str && str == "hello") {
    std::cout << "success";
}

Now decide whether you want to write code in C or C++, just don't mix it . 现在,决定是否要使用C或C ++编写代码,只是不要混合使用

while((strcmp(ready, "Ready")||strcmp(ready, "ready"))!=0)

should be 应该

while(strcmp(ready, "Ready") != 0 && strcmp(ready, "ready") != 0)

The version you wrote will always be true. 您编写的版本将永远是真实的。

Here's how to do some basic debugging, such as checking exactly what you input. 这是进行一些基本调试的方法,例如准确检查您输入的内容。

using namespace std; 

char* string = new char[6];
cin >> string;

for(int i=0; i<6; ++i)
{
    printf("[%d]: Hex: 0x%x;  Char: %c\n", i, string[i], string[i]);
}

while(strcmp(string, "hello")==0)
{
   cout << "success!";
}

I suspect that your input is something other than hello , (such as hello\\n , or hello\\r\\n , or maybe even ( unicode ) hello , which makes the strcmp fail. 我怀疑您的输入不是hello ,例如hello\\nhello\\r\\n ,甚至( unicodehello ,这会使strcmp失败。

But rather than me guessing, you can check for yourself using the simple printf above. 但是,不用我猜测,您可以使用上面的简单printf检查自己。

If you can come back with the exact Hex dump of your input, and state that strcmp still doesn't work as expected, then we'll have something worth investigating. 如果您可以返回输入的确切十六进制转储,并且指出strcmp 仍然无法按预期工作,那么我们将有一些值得研究的地方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM