Question:
Comparing 2 Chars in C++?
Ryan J
2007-12-18 16:15:15 UTC
I have been trying to compare 2 chars in C++ such as:
#include
#include
#include
char coo1[256];
char coo2[256];
int main () {
cin >> coo1
cin >> coo2
if (coo1 == coo2){
cout << "Cool it worked" << 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?
Three answers:
David B
2007-12-18 16:28:18 UTC
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.
laranjeira
2016-11-23 18:21:46 UTC
on account that greet is a char, it may carry a single character. in case you like distinctive characters, you like an array of characters. in spite of the shown fact that, C & C++ do no longer define assessment for arrays of characters by default -- it is you won't be able to apply ==. as a substitute you employ a functionality like strcmp, write your guy or woman, or use a string type which does help ==.
?
2007-12-18 17:18:11 UTC
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.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...