首页 > 解决方案 > 如何使用带有 char 条件的 if 语句将 int 值插入矩阵?

问题描述

我正在学习 C 并且在这种情况下遇到了麻烦,我需要根据用户字符输入将值放入矩阵中,这是代码:

#include <stdlib.h>
#include <stdio.h>

int main() {

    int mat[2][2] = { NULL };
    char sex;

    printf("Insert gender (m or f):");
    scanf_s("%c", &sex);
    if (&sex == "m") {
        mat[0][0] = 1;
        }
    if (&sex == "f") {
        mat[0][0] = 2;
    }
    else{
        mat[0][0] = 3;
        printf("invalid\n");
    }
    printf("inserted: %c \n", sex);

    printf("value on matrix 00: %i\t", mat[0][0]);
    //printf("%i\n", mat[0][1]);
    //printf("%i\t", mat[1][0]);
    //printf("%i", mat[1][1]);

    return 0;
}

最后的值似乎是正确的,但程序没有按我预期的那样运行,我看不到我的错误,有什么帮助吗?

标签: c

解决方案


在 C 中,运算符 == 不能用于比较字符串。为此,您应该使用string.h中的strcmp函数。无论如何,您需要的不是比较字符串,而是比较字符(而您正在做的是将地址与字符串进行比较)。我的建议:扫描 char 而不是字符串(使用scanf而不是scanf_s)并将相等测试从&var == "val"更改为var == 'val'。以下代码中还有一些提示:

#include <stdlib.h>
#include <stdio.h>

int main()
{
    //name your variables properly
    //initialize them immediately to avoid undefined values
    //respect its types: use '\0' instead of 0 for chars, and 0 instead of NULL for ints

    char gender = '\0';
    int matrix[2][2] = {{0, 0}, {0, 0}};
    
    //display accurate messages to the user
    
    printf("Select a gender (m or f): ");
    
    //don't scan a string if you only need a char
    //always check the return of a scan
    
    if(scanf("%c", &gender) <= 0)
    {
         printf("Input error\n");
         return 0;
    }
    
    //switch is usually more efficient than else-ifs
    
    switch(gender)
    {
        case 'm':
            matrix[0][0] = 1;
            break;
        
        case 'f':
            matrix[0][0] = 2;
            break;
        
        default:
            printf("Invalid gender\n");
            return 0;
    }
    
    printf("Selected gender: %c\n", gender);
    printf("Value on matrix[0][0]: %d\n", matrix[0][0]);
    
    return 0;
}

推荐阅读