Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ won't let me compare pointer and int

Tags:

c++

string

So I'm learning C++ and I'm trying to learn how to manipulate strings and such, in this code segment, I am looking to present a particular string with no spaces:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string intro = "Hello my name is John";
    for(string::iterator it = intro.begin(); it != intro.end(); ++it) {
        if((*it) != " ") {
            cout << *it;
        }
    }

    return 0;
}

I'm completely oblivious to what I'm doing wrong here. Can anyone help? I haven't used any integers and the error says "ISO C++ forbids comparison between pointer and int"

like image 788
HJGBAUM Avatar asked Dec 02 '22 13:12

HJGBAUM


1 Answers

The problem is that " " (double quotes) is not a single space character. It is a string literal that consists of a space character and a null terminator.

The type of a string literal is const char[], which decays into a const char* for the comparison. A single char, on the other hand, is a numeric type, which gets promoted to an int for comparison. This is the reason the compiler tells you that you are trying to compare a pointer to an int.

You need to replace " " with ' ' (single quotes), which is a single char, in order for your program to compile.

like image 97
Sergey Kalinichenko Avatar answered Dec 07 '22 22:12

Sergey Kalinichenko