【问题标题】:Char comparison on if statement doesn't evaluate to trueif 语句的字符比较不评估为 true
【发布时间】:2017-04-08 09:46:50
【问题描述】:

为什么即使 sex[i] 具有 M char 的值,以下 IF 语句的计算结果也不为真?

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

我要做的是创建一个字符数组,其中包含字符串或字符的多个值。在这种情况下,它是一个字符并且它在 if 函数之外工作,如果我打印 sex[0] 我得到 M。

哦,我知道变量需要这样声明

char sex[size][sizeofstring]

整个代码:

#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]);
}

【问题讨论】:

  • 等等,你为什么要分配一个二维数组?
  • 因为我在谷歌上搜索了如何为 char 创建一个数组,这就是他们告诉我的。我假设第二个维度将保存字符串具有的字符数量,第一个维度是您希望数组具有多少个字符串。
  • 那么,试试if (*sex[i] == 'M' || *sex[i] == 'm')
  • 因为sex[i]是一个字符串,而'M'或'm'只是一个字符(?)

标签: c if-statement char comparison


【解决方案1】:

鉴于声明

char sex[size][sizeofstring];

使用

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

不起作用,因为它变成了指针比较操作。相当于:

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 )

这就解释了为什么if 语句中的条件永远不会计算为真。

解决方案

你应该使用:

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

如果你的编译器支持非标准的不区分大小写的字符串比较函数stricmp,你可以将这两个测试结合起来。

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

【讨论】:

  • 奇怪的是,当我使用你刚刚给我的 strcmp 函数时,它只打印出 M 的 2/3 值。 if (*sex[i] == 'M' || *sex [i] == 'm') 虽然是 3/3。
  • @AlexRD, *sex[i] == 'M' 是一个不太严格的测试。只要sex[i][0] 中的值是'M',它将评估为true,无论sex[i][1] 中的内容是什么。
  • 您可以使用stricmp()组合这两个测试。
  • @AlexRD 使用%s 而不是%c
  • @AlexRD,当您使用%c 时,只会读取一个字符。当您使用%s 时,将读取一个字符串。如果该字符串恰好包含一个字符,则该字符串仍为空终止。因此,strcmp 有效。
【解决方案2】:

这里是长版:

char arr[size_1][size_2]

表示我要存储stringS(复数)。

arr[i]

表示我要访问第 i 个字符串

arr[i][j]

表示我要访问第 i 个字符串的第 j 个字符。

试试这个:

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]);

【讨论】:

    猜你喜欢
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 2013-06-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 1970-01-01
    相关资源
    最近更新 更多