سؤال

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?

هل كانت مفيدة؟

المحلول 2

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.

نصائح أخرى

C-style approach:

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

C++ approach:

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.

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.

But rather than me guessing, you can check for yourself using the simple printf above.

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top