我正在尝试使用 C++ 创建凯撒密码。我已将程序读入文本文件,但我需要它来加密文本并输出到屏幕。
这是我的加密代码,但我似乎无法让它工作。我才刚刚开始使用 C++,并不确定从这里到哪里去。
cout << "enter a value between 1-26 to encrypt the text: ";
cin >> shift;
while ((shift <1) || (shift >26)) {
cout << "Enter a value between 1 and 26!: ";
cin >> shift;
}
int size = strlen(text);
int i=0;
for(i=0; i<size; i++) {
cipher[i] = (text[i]);
if (islower(text[i])) {
if (text[i] > 122) {
cipher[i] = ( (int)(text[i] - 26) + shift);
}
} else if (isupper(text[i])) {
if (text[i] > 90) {
cipher[i] = ( (int)(text[i] - 26) + shift);
}
}
}
cipher[size] = '\0';
cout << cipher << endl;
最佳答案
首先,你的算法是错误的。
如果我们假设 ASCII input 那么您需要加密 32(即空格)和 126(即波浪号〜)之间的值,包括在内。您可以通过将键(单个数字)添加到值来执行此操作。如果结果大于 126(您的最大可用字符),您需要回绕并从 32 开始计数。这意味着 126 + 1 = 32、126 + 2 = 33,等等。查找“模数”。
我建议您查找“调试”一词。通常,当你有一个算法时,你会尽可能地编写与该算法匹配的代码。如果结果不是预期的结果,那么您将使用调试器逐行执行,直到您发现该行是您的预期结果并且您的代码结果不再匹配。
关于c++ - 凯撒密码输入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13708431/