0

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?

4

3 回答 3

3

C 风格的方法:

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

C++ 方法:

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

现在决定是用 C 还是 C++ 编写代码,只是不要混合使用

于 2013-09-28T22:25:50.227 回答
2
while((strcmp(ready, "Ready")||strcmp(ready, "ready"))!=0)

应该

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

你写的版本永远是真的。

于 2013-09-28T22:53:06.190 回答
1

以下是如何进行一些基本调试,例如准确检查您输入的内容。

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!";
}

我怀疑您的输入不是hello, (例如hello\n, or hello\r\n, 甚至可能是 ( unicode ) hello,这会导致strcmp失败。

但不是我猜测,您可以使用printf上面的简单方法自行检查。

如果您可以返回输入的确切十六进制转储,并指出strcmp 仍然无法按预期工作,那么我们将有一些值得调查的事情。

于 2013-09-28T22:33:50.783 回答