[英]Why isn't “0” == “0”?
我在這個項目中沒有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"
。
因為你要比較指針,而不是字符串。 要比較字符串A)只是比較std::string
而不是使用c_str()
(最好),或者B)使用strcmp
。
這是一個指針比較。 對於原始char*
比較使用strcmp
。 如果strcmp
不相等則返回-1或1,如果它們相等則返回0。
input.str().c_str()
返回const char*
,它只是一個指針值,實際上是一些地址,如0x1233abcd。 “0”也是const char*
類型,它也是一個指針並且有一些地址即。 0x6533ab3d。 當您執行比較時:
if(input.str()。c_str()!=“0”)
那么它就像比較指針值(地址),所以就像它一樣
if(0x1233abcd!= 0x6533ab3d)
你會一直都是真的
正如在這個if語句中已經說過的那樣
if(input.str().c_str() != "0") //Runs even though it shouldn't
{
input << number;
}
比較字符串c_str()和字符串文字“0”的第一個元素的地址。 由於他們有不同的地址,他們總是不平等,條件總是如此。
我想你的意思
if(input.str().c_str()[0] != '\0')
{
input << number;
}
正如其他人所說,你正在比較原始char*
指針,它們具有不同的地址,因為它們來自不同的來源。 要做你正在嘗試的事情,你需要使用std::string::operator==()
來比較std::string
的內容而不是比較指針(並且還要去除對std:stringstream::str()
的冗余調用std:stringstream::str()
,你所做的只是浪費內存):
void calc::AddToInput(int number)
{
std::string str = input.str();
MessageBox(NULL, str.c_str(), "Input", NULL);
if (str == "0")
input.str("");
input << number;
}
或者,如果你也擺脫了MessageBox()
:
void calc::AddToInput(int number)
{
if (input.str() == "0")
input.str("");
input << number;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.