I am trying to compile the following code on Ubuntu (64-bit), with Code::Blocks 10.05 as IDE:
#include
using namespace std;
int main() {
char a[2]
defines an array of char
's. a
is a pointer to the memory at the beginning of the array and using ==
won't actually compare the contents of a
with '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 typeid
of '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
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:
#include <iostream>
#include <string>
using namespace std;
int main(){
string a;
cout<<"enter ab ";
cin>>a;
if(a=="ab"){
cout<<"correct";
}
return 0;
}
This one is due to:
if(a=='ab')
, here, a
is const char*
type (ie : array of char)
'ab'
is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.
Since char
is a primitive type inherited from C, no operator ==
is defined.
the good code should be:
if(strcmp(a,"ab")==0)
, then you'll compare a const char*
to another const char*
using strcmp
.
In your code,you wrote char a[2]; which is wrong.You shoud've wrote char* a[2]; Then you can get your proper output.
In DEVC++, I faced same issue and i got solution. I used single quote instead of double quote.