Tuesday, July 28, 2009

Comparing 2 Chars in C++?

I have been trying to compare 2 chars in C++ such as:


#include %26lt;stdio.h%26gt;


#include %26lt;string.h%26gt;


#include %26lt;iostream%26gt;


char coo1[256];


char coo2[256];


int main () {


cin %26gt;%26gt; coo1


cin %26gt;%26gt; coo2


if (coo1 == coo2){


cout %26lt;%26lt; "Cool it worked" %26lt;%26lt; endl;


}


}


of course i simplified my actual code, but i can't seem to get it to compare 2 char's is there some way to do it?

Comparing 2 Chars in C++?
You cannot do that because in C++ you are actually comparing the pointers and not the array of characters. In order to compare two strings you will need to include string.h and use the strcmp function. The strcmp function takes two parameters and returns -1 if the first is less than the second, 0, if they are equal, and 1 if the first is larger.





int result=strcmp(coo1, coo2);





There are also several other variants to compare the first x characters, compare without case sensitivity, etc.
Reply:You aren't comparing 2 chars. You are comparing 2 char arrays.


Like the other guy said, you can either do this with Strings, or compare each character in your char array


If you had:


char ltr = 'a';


char ltr2='b';


you can then do


if(ltr==ltr2)


because it is then comparing the ascii values.


With the built in string compare it does the same thing.





So if you want to compare 2 char arrays, you are going to have to loop them.


No comments:

Post a Comment