Page 1 of 1

Comparing a Char Z88

Posted: Thu Sep 02, 2021 7:14 am
by Jbizzel
I know this must be so easy, but I can't get it to work!


I have an unsigned char Hands[] which sometimes contains the letter 'Q' I want to do a check and if it contains 'Q' then print 'Qu' else print whatever is in Hands - But my code below doesn't work.

I also tried if (Hands=="q'){etc} - which didn't work either. I'm sure it must be something so simple that I'm doing wrong =(

Code: Select all

for( i = 13 ; i < n ; i++ ) {
         test = strcmp(Hands[i],'q');
         if (test = 0){printf("qu");}
         else{printf("%c ", Hands[i]);} 
         }

Re: Comparing a Char Z88

Posted: Thu Sep 02, 2021 2:14 pm
by dom
You're looking for this function: https://man7.org/linux/man-pages/man3/strchr.3.html

Re: Comparing a Char Z88

Posted: Thu Sep 02, 2021 3:03 pm
by derekfountain
strcmp() compares two strings, you're trying to use it to compare two characters. Since characters are simple 8-bit integer values in C you can compare them directly:

Code: Select all

if( Hands[i] == 'q' )
...
Also, C uses == for comparison and single = for assignment, so

Code: Select all

if (test = 0)
should be

Code: Select all

if (test == 0)
if it were needed.

Re: Comparing a Char Z88

Posted: Thu Sep 02, 2021 3:14 pm
by jorgegv
You are mixing C chars and strings here.

The strcmp you are doing expects 2 pointer arguments, but the second one is a char (single quoted), not a string. This is being promoted to an int (81, which is the ASCII for 'q'). So the strcmp does not do what you want.

The check "( test = 0)" is also wrong because you are not comparing test to 0, but assigning 0 to test ('=' is C assignment operator). You should use '==' here.

Your code should look more like this:

Code: Select all

for( i = 13 ; i < n ; i++ ) {
         if (Hands[i] == 'q'){printf("qu");}
         else{printf("%c ", Hands[i]);} 
         }
Or better yet, use the strchr function, as @Dom suggested.

Re: Comparing a Char Z88

Posted: Thu Sep 02, 2021 3:46 pm
by jorgegv
Whoa, synchronized thinking...

Re: Comparing a Char Z88

Posted: Thu Sep 02, 2021 9:00 pm
by Jbizzel
Thanks guys for your help. I see my many errors and have got it working now with your help.