1

I'm new to C++.

string str = "WWWHBBB";
if(str[mid] == "H" && str[0] != "W") return; // corrected after comments for second operand

The above line with if condition gives me an error.

Comparison between pointer and integer ('std::__1::basic_string, std::__1::allocator >::value_type' (aka 'char') and 'const char *')

I have searched the internet enough to know that array style access is fine in strings. Error basically is pointing out comparison about pointer and integer. Really? I thought I was comparing character H to another character in string str.

I tried if str[mid] really returns an iterator I should do *str[mid]. Nah! Didn't work either.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
HalfWebDev
  • 7,022
  • 12
  • 65
  • 103

2 Answers2

3

You'd want to compare with a single char

if (str[mid] == 'H' && str[mid] != 'W') return;

Note that double-quotes in this case refer to a const char[] whereas single-quotes refer to a single char.

The warning is telling you that the only way to make those comparisons in your case would be to compare the lhs char (result of str[mid]) to the rhs would be to let the array decay to const char* and compare the pointer address to the char.

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
3

In the expression of the if statement

 if(str[mid] == "H" && str[mid] != "W") return;

the string literals "H" and "W" that have the type const char[2] are implicitly converted to pointers to their first characters of the type const char *.

So you are trying to compare a character returned by the expression str[mid] with a pointer.

Instead of the string literals you need to use character literals like to compare characters

 if(str[mid] == 'H' && str[mid] != 'W') return;

You could also write like

 if(str[mid] == *"H" && str[mid] != *"W") return;

or

 if(str[mid] == "H"[0] && str[mid] != "W"[0]) return;

dereferencing the pointers but this will be confusing

Pay attention to that if str[mid] == 'H' then the second operand will always yield true. So it is enough to write

 if( str[mid] == 'H' ) return;
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335