为什么不是"0"=="0"?

Tob*_*ell 4 c++ winapi stringstream

我在这个项目中没有UNICODE.这是一个WinAPI项目,变量"input"是一个字符串流,默认值为"0".为什么第一个id语句运行而不是第二个,即使字符串本身为"0"?

void calc::AddToInput(int number)
{
    MessageBox(NULL, input.str().c_str(), "Input", NULL); //Shows "0"

    if(input.str().c_str() != "0") //Runs even though it shouldn't
    {
        input << number;
    }
    else if(input.str().c_str() == "0") //Doesn't run though it should
    {
        input.str("");
        input << number;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jos*_*eld 18

比较C风格的字符串,==意味着"这些字符串的第一个元素是否具有相同的地址?".它实际上并不比较字符串的内容.为此,你需要strcmp.

但是,你没有理由比较C风格的字符串 - 只需使用std::string返回的from str(),可以使用它进行比较==,如下所示:input.str() != "0".

  • @TobiasSundell _我们的techer没有通知我们... _有一个从`const char*`到`std :: string`的隐式构造函数,也许你没有注意到你的老师或你的教科书告诉你的后果**那**!;)... (2认同)

Ed *_* S. 5

因为你要比较指针,而不是字符串.比较字符串A)只是比较std::string而不是使用c_str()(最佳)或B)使用strcmp.