【发布时间】:2015-05-11 21:35:53
【问题描述】:
对于课堂,我必须用 C++ 开发一个 Caesar 加密项目,该项目接受一个字符串,并将所有 ascii 代码移动一个随机整数。我的项目运行良好,代码如下:
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main(int argc, const char * argv[]) {
string sentence = "";
int shifter, counter = 0, position = 0;
srand(time(NULL));
shifter = (rand() % 25) + 1;
cout << "Enter a sentence, and this program will encrypt it: " << endl;
getline(cin, sentence);
cout << "\n\n\n";
for (int i = 0; i < sentence.length(); i++) {
sentence[i] = sentence[i] + shifter;
cout << sentence[i];
}
return 0;
}
我唯一的问题是我的老师希望他们只改成字母。如果字母是“z”并且移位是“2”,她希望输出是“b”。我不确定如何做到这一点。
这个问题的简单程序可行吗?如果有,怎么做?
【问题讨论】:
-
你熟悉取模运算吗?
-
@iProgramIt 好的,那么 28 mod 26 是什么? 28 是 z + 2。
-
2 就是答案。
-
@iProgramIt 以及如何将
2映射到字母表的第三个字母(我们假设我们从0开始)? -
请,请,请在询问之前搜索:Possible duplicates of Caesar Cipher。我也回答了几个。
标签: c++ string encryption caesar-cipher