C语言实现ROT13加密时ASCII字符偏移出现异常字符问题
问题原因分析
- 头文件缺失:你使用了
tolower()函数但没有包含<ctype.h>头文件,会触发未定义行为。 - 核心报错原因:
char类型溢出。绝大多数C编译器默认char为有符号类型,取值范围为-128~127。当你对ASCII为122的'z'加6时,计算结果为128,超过有符号char的最大值,发生溢出后变为负数,你的判断条件while(words[i] > 122)永远不会触发,自然不会执行回绕逻辑,最终输出超出可打印范围的乱码。而偏移5位时122+5=127刚好落在有符号char的取值范围内,所以可以正常运行。 - 变量命名不规范:你直接用C标准库的类型名
size_t作为自定义变量名,属于不良编码习惯,容易引发命名冲突。 - 回绕逻辑冗余:不需要用
while循环处理回绕逻辑,用模26运算可以直接得到偏移后的结果,逻辑更清晰不易出错。
修复后参考代码
#include <stdio.h> #include <string.h> #include <ctype.h> // 补全tolower所需的头文件 int main(){ char words[25] = "ABC MNO XYZ"; const int offset = 6; printf("%s\n", words); int len = strlen(words); printf("size of 'words' is %d\n", len); for (int i=0; i < len; i++){ printf("%c\n", words[i]); } printf("unencrypted ends here...\n\nStarts the cipher\n"); // 转小写 for (int i=0; i < len; i++){ words[i] = tolower(words[i]); } for (int i=0; i < len; i++) { if(words[i] >= 'a' && words[i] <= 'z') { // 用模运算直接计算偏移后的值,避免溢出和循环 words[i] = (words[i] - 'a' + offset) % 26 + 'a'; } printf("%c\n", words[i]); } return 0; }
内容的提问来源于stack exchange,提问作者lilv
相关产品推荐
相关产品推荐

