Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dereferencing string iterator yields 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 the string iterator yield an int and not std::string?

like image 983
lo tolmencre Avatar asked Sep 15 '15 07:09

lo tolmencre


1 Answers

Actually, it does not yield an int, it yields a char (because a string iterator iterates over the characters in the string). Since the other operand of != is not a char (it's a const char[2]), standard promotions and conversions are applied to the arguments:

  • char is promoted to int via integral promotion
  • const char[2] is converted to const char* via array-to-pointer conversion,

This is how you arrive at the int and const char* operands the compiler is complaining about.

You should compare the dereferenced iterator to a character, not to a string:

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

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

like image 192
Angew is no longer proud of SO Avatar answered Sep 22 '22 10:09

Angew is no longer proud of SO