I am trying to compile the following code on Ubuntu (64-bit), with Code::Blocks 10.05 as IDE:
#include <iostream>
using namespace std;
int main() {
char a[2];
cout << "enter ab ";
cin >> a;
if (a == 'ab') // line 7
{
cout << "correct";
}
return 0;
}
On line 7, my compiler gives me the error “ISO C++ forbids comparison between pointer and integer [-fpermissive]”.
Why doesn’t this work? I know I could use an std::string to work around the problem, but I want to understand the current problem.
char a[2]defines an array ofchar‘s.ais a pointer to the memory at the beginning of the array and using==won’t actually compare the contents ofawith'ab'because they aren’t actually the same types,'ab'is integer type. Also'ab'should be"ab"otherwise you’ll have problems here too. To compare arrays of char you’d want to use strcmp.Something that might be illustrative is looking at the
typeidof'ab':on my system this returns:
showing that
'ab'is actually evaluated as an int.If you were to do the same thing with a std::string then you would be dealing with a class and std::string has
operator ==overloaded and will do a comparison check when called this way.If you wish to compare the input with the string “ab” in an idiomatic c++ way I suggest you do it like so: