ISO C ++ prohibits comparison between pointer and integer [-fpermissive] | [C ++]

I am trying to compile the following code on Ubuntu (64-bit), with the code :: Blocks 10.05 as an 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 ++ prohibits comparison between pointer and integer [-fpermissive]".

Why is this not working? I know that I could use std::string to solve this problem, but I want to understand the current problem.

+8
c ++
source share
2 answers

char a[2] defines a char array. a is a pointer to memory at the beginning of the array, and using == will not actually compare the contents of a with 'ab' , because they are actually not the same types, 'ab' is an integer type. Also, 'ab' should be "ab" , otherwise you will also have problems. To compare char arrays, you want to use strcmp.

Something that might be illustrative is to look at typeid 'ab' :

 #include <iostream> #include <typeinfo> using namespace std; int main(){ int some_int =5; std::cout << typeid('ab').name() << std::endl; std::cout << typeid(some_int).name() << std::endl; return 0; } 

on my system, this returns:

 i i 

indicating that 'ab' actually evaluated as int.

If you were to do the same with std :: string, then you would come across a class and std :: string with operator == overloaded and do a match check when calling this method.

If you want to compare the input with the string "ab" in C ++ idiomatic mode, I suggest you do it like this:

 #include <iostream> #include <string> using namespace std; int main(){ string a; cout<<"enter ab "; cin>>a; if(a=="ab"){ cout<<"correct"; } return 0; } 
+12
source share

It's connected with:

if(a=='ab') , here a is of type const char* (i.e. an array from char)

'ab' is a constant value that is not evaluated as a string (due to a single quote), but will be evaluated as an integer.

Since char is a primitive type inherited from C, the == operator is not specified.

good code should be:

if(strcmp(a,"ab")==0) , then you compare const char* with another const char* with strcmp .

+5
source share

All Articles