0

I am currently something something like this

std::map<std::string,std::string>::iterator it ;
for(it=mmap.begin();it!=mmap.end();it++)
{
    if(it->second.c_str() != "qa" && it->second.c_str() != "qb")
    {
        //Entered
    }
}

Now the problem with this code is that it goes into the entered section even when the iterator is

it("Testing this","qb")

Thee above means that it->second = "qb"

Now my question is why is the code going ino the if statement if it->second = "qb" My thought is that it should not have because the conditional statment part is it->second.c_str() != "qb"

Rajeshwar
  • 11,179
  • 26
  • 86
  • 158

2 Answers2

3

The problem is because it->second.c_str() != "qa" is not the correct way to compare C strings (it compares pointers and not the string contents). You however do not need to convert to a C string first before comparing as you can compare the strings directly with: it->second != "qa". If you for some reason need to use the c string with c_str() then you will need to use strcmp.

shuttle87
  • 15,466
  • 11
  • 77
  • 106
3

c_str() is a character array (pointer), so you are comparing two pointers which are different.

Use string objects instead:

std::string QA("qa");
std::string QB("qb");
std::map<std::string,std::string>::iterator it ;
for(it=mmap.begin();it!=mmap.end();it++)
{
    if(it->second != QA && it->second  != QB)
    {
        //Entered
    }
}

or actually do C style string compare:

    if ( strcmp(it->second.c_str(), "qa") != 0 && strcmp(it->second.c_str(), "qb") != 0 )
Brad
  • 3,190
  • 1
  • 22
  • 36