Comparing a Char Z88

Discussion about other targets
Post Reply
Jbizzel
Member
Posts: 14
Joined: Tue Jun 29, 2021 7:20 pm

Comparing a Char Z88

Post 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]);} 
         }
User avatar
dom
Well known member
Posts: 2076
Joined: Sun Jul 15, 2007 10:01 pm

Re: Comparing a Char Z88

Post by dom »

You're looking for this function: https://man7.org/linux/man-pages/man3/strchr.3.html
derekfountain
Member
Posts: 121
Joined: Mon Mar 26, 2018 1:49 pm

Re: Comparing a Char Z88

Post 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.
User avatar
jorgegv
Well known member
Posts: 287
Joined: Wed Nov 18, 2020 5:08 pm

Re: Comparing a Char Z88

Post 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.
User avatar
jorgegv
Well known member
Posts: 287
Joined: Wed Nov 18, 2020 5:08 pm

Re: Comparing a Char Z88

Post by jorgegv »

Whoa, synchronized thinking...
Jbizzel
Member
Posts: 14
Joined: Tue Jun 29, 2021 7:20 pm

Re: Comparing a Char Z88

Post by Jbizzel »

Thanks guys for your help. I see my many errors and have got it working now with your help.
Post Reply