C++实现XOR加密程序无法加密完整输入句子问题求助
问题原因与修复方案
- 缓冲区溢出:你声明的
message数组容量仅为300,但调用cin.get(message, 500)时允许最多读取499个字符,超出数组容量的写入会破坏后续内存中的数据(比如密钥内容、全局变量x/y的值),直接导致加密逻辑中断。修复方式将读取长度改为和数组容量匹配,比如改为cin.get(message, 300)。 - 输出显示异常:XOR运算的结果可能是ASCII码小于32的控制字符(比如退格、空终止符、换页符等),直接输出到控制台时,这些控制字符会干扰正常显示,让你误以为只加密了部分输入,实际上加密逻辑已经跑完了。如果要验证加密完整性,可以将加密后的字符转为十六进制数值输出,就能看到完整结果。
- 语法不规范隐患:
- 第一行头文件引入缺少
#,正确写法为#include <stdio.h> - 标准C++要求main函数必须指定返回值类型,应改为
int main() - 使用
exit函数需要引入对应头文件,添加#include <cstdlib> - 仅在加密函数内使用的x、y、cipher变量建议定义为函数局部变量,避免全局变量被意外修改的风险。
- 第一行头文件引入缺少
修复后参考代码
#include <stdio.h> #include <iostream> #include <cstdlib> using namespace std; void encrypt_stand_message(); int option = 0; char message[300]; char key[] = "ALCtALC sixth headed civic outlying mayflower irregular boneless prevail freebase delirious projector dreamless"; int main () { cout << "Plese choose option?" << "\n\n"; cout << "1. Cipher text\n\n"; cout << "\n"; cin >> option; switch(option){ case 1: encrypt_stand_message(); exit(1); } return 0; } void encrypt_stand_message(){ system("clear"); cout << "Please enter the code to encrypt?" << "\n\n"; cin.ignore(); cin.get(message, 300); int x = 0, y = 0; char a = message[x]; char b = key[y]; while(a != '\0'){ char cipher = a ^ b; // 若要查看可打印的加密结果,可以替换为下面的十六进制输出 // cout << hex << (int)(unsigned char)cipher << " "; cout << cipher; x += 1; y += 1; a = message[x]; if(key[y] == '\0'){ y = 0; } b = key[y]; } }
内容的提问来源于stack exchange,提问作者Alejo094
相关产品推荐
相关产品推荐

