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"
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.
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