Why not "0" == "0"?

I do not have UNICODE in this project. This is a WinAPI project, and the variable "input" is a string stream with a default value of "0". Why is the first id statement executed and not the second, although the string itself has a value of "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;
    }
}
+4
source share
6 answers

Comparing C-style strings with ==means "Do the first elements of these strings have the same address?" In fact, this does not compare the contents of the strings. For this you need strcmp.

C- - std::string, str(), ==, : input.str() != "0".

+18

, . , A) std::string c_str() ( ), B) strcmp.

+5

. char* strcmp. strcmp -1 1, , 0, .

+3

input.str().c_str() const char*, , , 0x1233abcd. "0" const char*, , . 0x6533ab3d. , :

if (input.str(). c_str()!= "0" )

() ,

if (0x1233abcd!= 0x6533ab3d)

.

+3

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;
}
+2

As others have said, you are comparing raw pointers char*that have different addresses, since they come from different sources. To do what you are trying, you need to use std::string::operator==()instead to compare the contents std::stringand not compare the pointers (and also get rid of redundant calls std:stringstream::str(), all you do is lose memory this way):

void calc::AddToInput(int number)
{
    std::string str = input.str();

    MessageBox(NULL, str.c_str(), "Input", NULL);

    if (str == "0")
        input.str("");

    input << number;
}

Or, if you also get rid of MessageBox():

void calc::AddToInput(int number)
{
    if (input.str() == "0")
        input.str("");

    input << number;
}
0
source

Source: https://habr.com/ru/post/1523962/


All Articles