#include<iostream> #include<string> using namespace std; class words { private: string word; string key; public: words() {} words(string w, string k) :word(w), key(k) {} void setWord(string w) { word = w; } void setKey(string k) { key = k; } friend string operator^(const words& w1, const words& w2) { int length = w1.word.length(); string result; for (int i = 0; i < length; i++) { result += w1.word[i] ^ w2.key[i % w2.key.length()]; } return result; } }; int main() { words w("", ""); //初始化一个words对象 string word; string key; int n; cout << "请输入想要加密解密的字符串的个数:" << endl; cin >> n; cout << "请输入密钥:" << endl; cin >> key; w.setKey(key); for (int i = 0; i < n; i++) { string result1; string result2; cout << "请输入需要加密的字符串:" << endl; cin >> word; w.setWord(word); cout << "加密后为:" << endl; result1 = w ^ w; cout << result1 << endl; cout << "解密后为:" << endl; result2 = w ^ w; cout << result2 << endl; } system("pause"); return 0; }将上面的代码做一点修改使得可以加密解密
时间: 2023-11-27 15:49:20 浏览: 45
使用include <iostream>时一定要加using namespace std
可以按照以下方式修改代码,添加加密和解密函数:
```
#include<iostream>
#include<string>
using namespace std;
class words {
private:
string word;
string key;
public:
words() {}
words(string w, string k) :word(w), key(k) {}
void setWord(string w) { word = w; }
void setKey(string k) { key = k; }
// 加密函数
string encrypt() {
int length = word.length();
string result;
for (int i = 0; i < length; i++) {
result += word[i] ^ key[i % key.length()];
}
return result;
}
// 解密函数
string decrypt() {
int length = word.length();
string result;
for (int i = 0; i < length; i++) {
result += word[i] ^ key[i % key.length()];
}
return result;
}
};
int main() {
words w("", ""); //初始化一个words对象
string word;
string key;
int n;
cout << "请输入想要加密解密的字符串的个数:" << endl;
cin >> n;
cout << "请输入密钥:" << endl;
cin >> key;
w.setKey(key);
for (int i = 0; i < n; i++)
{
string result1;
string result2;
cout << "请输入需要加密的字符串:" << endl;
cin >> word;
w.setWord(word);
cout << "加密后为:" << endl;
result1 = w.encrypt();
cout << result1 << endl;
cout << "解密后为:" << endl;
result2 = w.decrypt();
cout << result2 << endl;
}
system("pause");
return 0;
}
```
在上述代码中,我们添加了两个函数:`encrypt()` 和 `decrypt()`。`encrypt()` 函数将输入的字符串进行加密,返回加密后的结果;`decrypt()` 函数将加密后的字符串进行解密,返回解密后的结果。这样,我们就可以在主函数中调用这两个函数来进行加密和解密操作。
阅读全文