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?
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 promotionconst 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With