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"

2
  • 3
    try if(it->second != "qa" && it->second != "qb"). Commented Jul 29, 2014 at 21:41
  • Possible Duplicate Commented Jul 29, 2014 at 21:48

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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 ) 

2 Comments

You can compare directly on the right hand side with a null-terminated C-string, no need for QA and QB.
If you are going to have a QA and a QB, they should be declared as constant strings.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.