我有一个简单的程序,它接受一个文件并加密它,直到你回答两个问题,但文件永远不会被解密。
char normal[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
char encrypted[] = {'t', 'h', 'e', 'q', 'u', 'i', 'c', 'k', 'b', 'r', 'o', 'w', 'n', 'f', 'x', 'j', 'u', 'm', 'p', 'd', 'v', 'l', 'a', 'z', 'y', 'g'};
int main() {
cout << "Welcome to file proofreader!" << endl << "Once you choose a file, we will proofread it and return a copy to you with our" << endl << "corrections." << endl;
cout << "Please choose a file to proofread: ";
string filename;
cin >> filename;
encrypt(filename);
cout << "GOTCHA! Your file has been encrypted. Your file will be lost forever unless you answer the following questions correctly!" << endl;
complete = quiz();
decrypt(filename);
cout << "Fine, I guess you can have your file back. " << endl;
return 0;
}
void encrypt(string filename) {
ifstream input;
input.open(filename.c_str());
ofstream output;
output.open("GOTCHA.txt");
char c;
while (input.get(c)) {
tolower(c);
output << encrypted[c-97];
}
input.close();
output << endl;
output.close();
ofstream other;
other.open(filename);
other << "GOTCHA!" << endl;
other.close();
}
void decrypt(string filename) {
ifstream input;
input.open("GOTCHA.txt");
ofstream output;
output.open(filename.c_str());
char c;
while (input.get(c)) {
int idx = findIdxInEncrypted(c);
output << normal[idx];
}
input.close();
output << endl;
output.close();
}
int findIdxInEncrypted(char c) {
for (int i = 0; i < 26; i++) {
if (c == encrypted[i]) {
return i;
}
}
}
bool quiz (){
cout << endl;
cout << "What color is the sky? " << endl << endl;
cout << "A) Blue" << endl;
cout << "B)/> Green" << endl;
cout << "C) Red" << endl;
cout << "D) Purple" << endl;
char answer;
cin >> answer;
if (answer == 'a' || answer == 'A') {
cout << "Correct" << endl;
}
else
cout << "Incorrect" << endl;
cout << endl;
cout << "What color is grass? " << endl;
cout << "A) Blue" << endl;
cout << "B)/> Green" << endl;
cout << "C) Red" << endl;
cout << "D) Purple" << endl;
cin >> answer;
if (answer == 'b' || answer == 'B'){
cout << "Correct" << endl;
}
else
cout << "Incorrect" << endl;
cout << endl;
return true;
}
GOTCHA.txt看起来像这样tkbp ^ @ fuuqp ^ @ dx ^ @ mvf ^ P并且传递给它的文件看起来像这样^ @需要^ @到^ @ run ^ @ ^ @。
假设说“这需要运行”。
答案 0 :(得分:2)
首先,@ molbdnilo提到你需要适当使用tolower。
int x = tolower(c);
output << encrypted[x - 97];
不要加密非字母字符。您可以使用isalpha()检查非字母字符 http://www.cplusplus.com/reference/cctype/isalpha/
请务必在解密时保留非字母字符,因为您不会加密它们。您只能在代码中加密小写字母。
即使在解密时也会提出检查字母的条件。
第三,我没有看到使用
complete = quiz();
您还没有建立任何类型的答案检查。检查答案是否正确是有意义的。你的函数quiz()总是会返回true。
如果您有任何疑问,请告诉我们:)