文件未解密

File not coming back decrypted

本文关键字:解密 文件      更新时间:2023-10-16

我有一个简单的程序,它可以获取一个文件并对其加密,直到你回答两个问题,但该文件永远不会被解密。

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,传递给它的文件看起来像这个ahis^@需要^@才能^@运行^@^@。

它应该说"这需要运行"。

首先,正如@molbdnilo所提到的,您需要适当地使用tolower。

int x = tolower(c);
output << encrypted[x - 97];

不要加密非字母字符。您可以使用isalpha()检查非字母字符http://www.cplusplus.com/reference/cctype/isalpha/

解密时一定要保持非字母字符不变,因为你不会加密它们。您只能对代码中的小写字母进行加密。

即使在解密时也设置了一个检查字母的条件。

第三,我看不到的使用

complete = quiz();

你还没有建立任何形式的答案检查。检查答案是否正确是有意义的。函数quiz()最终总是返回true。

如果您有任何问题,请告诉我:)