首页 > 解决方案 > 将字母与枚举进行比较

问题描述

试图做一个凯撒密码。

enum alfabeto{
    A=0,B,C,D,E,F,G,H,I,L,M,N,O,P,Q,R,S,T,U,V,Z         // 21
};

void cifra(char *string, int k){
    enum alfabeto letter;    // initialize the enum letter
    size_t i = 0;    // initialize counter
    while (*(string+i)!='\0'){    // while string is not ended
        letter = *(string+i);     // attempt to "link" the enum letter to the equivalent (already uppercased) char
        printf("%d", letter);
        letter = (letter+k) % 21;    // then it increases of a factor k and if it goes out of 21, it should take the right value
        printf(" %d\n", letter);
        ++i;
    }
}

输出:

$ ./"cesare" 

write the text:
>TEST

choose the factor k:
>2

84 8
69 14
83 7
84 8

这些值是错误的......也许是因为我无法将枚举值“链接”到一个字符......我怎么能这样做?c

标签: carraysstringenumschar

解决方案


    letter = *(string+i);     // attempt to "link" the enum letter to the equivalent (already uppercased) char

应该:

    letter = *(string+i) - 'A';     // attempt to "link" the enum letter to the equivalent (already uppercased) char

这样,“ A”将根据需要映射为零。


推荐阅读