c - 如何使用带有 char 条件的 if 语句将 int 值插入矩阵?

标签 c

我正在学习 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 中,运算符 == 不能用于比较字符串。为此,您应该使用 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;
}

关于c - 如何使用带有 char 条件的 if 语句将 int 值插入矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56979885/

相关文章:

c - vsnprintf 和 strerror : segmentfault?

c - ARM-linux4.3.2,无法打开PF_PACKET类型的socket

c - 防止循环中的无效数组输入

c - 如何将十六进制字符转换为\x90\x90这样的字节?

c - pthread_sigmask 干扰 GDB

c - 正确使用更改数据的自由功能

c - 我应该始终将 char[] 的最后一个值设置为 '\0' 吗?

c - Ruby 解释器嵌入到 C 代码中

c - C 中的多线程问题

c - 不支持的 16 位应用程序