Pregunta

I do not have UNICODE in this project. This is a WinAPI project and the variable "input" is a stringstream with the default value "0". Why does the first id statement run and not 2nd one even though the string itself IS "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;
    }
}
¿Fue útil?

Solución

Comparing C-style strings with == means "Do the first elements of these strings have the same address?". It doesn't actually compare the contents of the strings. For that, you need strcmp.

However, you have no reason to compare C-style strings - just use the std::string returned from str(), which can be compared using ==, like so: input.str() != "0".

Otros consejos

Because you're comparing pointers, not strings. To compare strings either A) just compare the std::string instead of using c_str() (best), or B) use strcmp.

It's a pointer comparison. For raw char* comparison use strcmp. strcmp returns -1 or 1 if they're unequal, and 0 if they're equal.

input.str().c_str()returns const char* which is simply a pointer value which actually is some adress like 0x1233abcd. "0" is also of type const char*, which is also a pointer and has some address ie. 0x6533ab3d. When you perform comparison like:

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

then its like comparing pointer values (addresses), so its like

if ( 0x1233abcd != 0x6533ab3d )

you will get true all of the time

As already was said in this if statement

if(input.str().c_str() != "0") //Runs even though it shouldn't
{
    input << number;
}

there is comparison of addresses of the first elements of string c_str() and string literal "0". As they have different addresses they are always unequal that is the condition is always true.

I think you meant

if(input.str().c_str()[0] != '\0') 
{
    input << number;
}

As others have said, you are comparing raw char* pointers, which have different addresses since they come from different sources. To do what you are attempting, you need to use std::string::operator==() instead to compare the contents of the std::string rather than comparing pointers (and also, get rid of the redundant calls to std:stringstream::str(), all you are doing is wasting memory that 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 get rid of the MessageBox() as well:

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

    input << number;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top