char和char之间的比较不起作用

问题描述 投票:0回答:1

我做了一次(非常糟糕的)尝试。

这是代码:

#include <stdio.h>
#include <string.h>

int main()
{
    char passphrase[20];
    printf("Welcome to first_level.\n");
    printf("Hello. What's your passphrase?\n");

    fgets(passphrase,20,stdin);

    passphrase[strcspn(passphrase, "\n")] = 0;

    if(strlen(passphrase) != 10){
        // you lost
    } else
    {
        int counter = 0;
        for(int i = 0; i < 10; i++)
        {
            char index = i;
            char currentChar = passphrase[i];
            //printf(passphrase[i]);
            printf("---\nindex: %d\nchar: %c\n",index, currentChar);
            if(index == currentChar){
                //printf("ass\n");
                counter++;
            }
        }
        if(counter == 10)
        {
            printf("Congrats!\n");
            return 0;
        }

        printf("counter %d\n", counter);
    }

    printf("You lost!\n");
    return 0;
}

从理论上讲,char比较应该有效。不幸的是,我相信将字符转换为int,然后进行比较。

在比较之前使用神奇的printf,我注意到如果我打印了数字(%d),则字符将> 48,而在打印字符时(%c - 就像提供的代码一样),字符编号被正确打印。

我想知道我怎么能这样做?我已经尝试了strcmp,但显然它需要一个字符串而不是一个字符。

c
1个回答
2
投票

C标准要求字符'0''1',...和'9'是连续的和连续的。所以我们知道'1'的值比'0'的值大1(和其他数字类似)。

考虑到上述因素,我们知道这一点

'0' - '0' == 0;
'1' - '0' == 1;
....
'9' - '0' == 9;

请注意,以上所有内容必须按照我的描述工作,无论是在基于ASCII的计算机上运行,​​还是在EBCDIC或Klingon上运行,或者其他什么。

因此,比较字符形式('0',...,'9')中的数字与整数值(0,...,9)只需从char中减去'0'

if (index == currentChar - '0') /* ... */;
© www.soinside.com 2019 - 2024. All rights reserved.