【发布时间】:2020-05-20 21:20:46
【问题描述】:
尝试使用凯撒密码。
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
【问题讨论】:
-
1) 为什么不是完整的字母表? 2) 为什么是
*(string+i)而不是string[i]? -
每个输入字母都被编码为ASCII值(例如
T->84),但是你的输出值限制在[0, 21)范围内,不对应与 ASCII 字母表。您需要将它们移回正确的范围;这通常通过添加'a'或'A'的“基础”值来完成,具体取决于输入的情况。 -
您需要一个字符查找字符数组来匹配您的枚举。 C 中的枚举名称没有反射。因为范围有中断,您还需要扫描该查找数组 O(n) 以查找该值,或者为缺少的字母添加填充以允许 O(1) 查找。
-
@MichaelDorgan 如何制作查找表?从来没有这样做过。
标签: c arrays string enums char