gpt4 book ai didi

c++ - 为什么不是 "0"== "0"?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:53:13 26 4
gpt4 key购买 nike

我在这个项目中没有 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;
}
}

最佳答案

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

但是,您没有理由比较 C 风格的字符串 - 只需使用从 str() 返回的 std::string,可以使用 进行比较>==,像这样:input.str() != "0"

关于c++ - 为什么不是 "0"== "0"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21391223/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com