Dereferencing row fighter gives int

I get this error

comparison between pointer and integer ('int' and 'const char *') 

For the following code

 #include <iostream> #include <sstream> #include <string> using namespace std; int main() { std::string s("test string"); for(auto i = s.begin(); i != s.end(); ++i) { cout << ((*i) != "s") << endl; } } 

Why does dereferencing a string iterator give an int rather than a std::string ?

+6
source share
1 answer

Actually, it does not give int , it gives char (because the iterator of the string iterates over the characters in the string). Since the other operand != Is not char (it is a const char[2] ), the standard arguments and conversions apply to the arguments:

  • char advances to int through integral advertising
  • const char[2] converted to const char* by converting the array to a pointer,

This is how you get into the operands of int and const char* , with which the compiler complains.

You should compare a dereferenced iterator with a character, not a string:

 cout << ((*i) != 's') << endl; 

"" contains a string literal (type const char[N] ), '' encloses a character literal (type char ).

+8
source

All Articles