简体   繁体   中英

Char comparison on if statement doesn't evaluate to true

Why doesn't the following IF statement evaluate to true, even though sex[i] has the value of M char?

for (i=0;i<3;i++)
if (sex[i] == 'M' || sex[i] == 'm')

What i'm trying to do, is create an array of characters that holds several values for strings or characters. In this case, it's a character and it works outside the if function, if i print sex[0] i get M.

Oh, and i know that the variable needs to be declared like this

char sex[size][sizeofstring]

The entire code:

#include <stdio.h>

int main() {
    char name[10][256], sex[10][256];
    int i;
    for (i=0;i<3;i++) {
        printf ("Insert the name of the person %d and her gender, M for male F for female\n", i+1);
        scanf("%s", name[i]);
        scanf(" %c", sex[i]);
    }
    for (i=0;i<3;i++)
        if (*sex[i] == 'M' || *sex[i] == 'm')
            printf ("\n%s", name[i]);
    for (i=0;i<3;i++)
        if (sex[i] == 'F' || sex[i] == 'f')
            printf ("\n%s", name[i]);
}

Here is the long version:

char arr[size_1][size_2]

means that I want to store stringS(plural).

arr[i]

means that I want to access the i'th string

arr[i][j]

means that I want to access the j'th character of i'th string.

Try this:

char sex[2][30] = {
{"My name is this"},
{"Your name is this"}};

printf("I'm a single character: %c\n", sex[0][5]);
printf("I'm a string, group of characters: %s\n", sex[0]);

Given the declaration

char sex[size][sizeofstring];

use of

if (sex[i] == 'M' || sex[i] == 'm')

does not work since it becomes a pointer comparison operation. It is equivalent to:

char* p = sex[i];
void* p1 = 78;   // Assuming ASCII encoding.
                 // 'M' is an int. The int is converted to a pointer.
void* p2 = 102;  // Again, assuming ASCII encoding
if ( p == p1 || p == p2 )

That explains why the conditional in the if statement never evaluates to true.

Solution

You should use:

if ( strcmp(sex[i], "M") == 0 || strcmp(sex[i], "m") == 0)

If your compiler supports the non-standard case insensitive string comparison function, stricmp , you can combine the two tests.

if ( stricmp(sex[i], "M") == 0 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM