在过去的几天里,我一直在研究我的凯撒密码软件,除了一些问题外,它几乎很棒。
这是软件的加密部分:
E.cpp
#include<iostream>
using namespace std;
int main()
{
char message[100], ch;
int i, key;
cout << "Enter a message to encrypt: "<<endl;
cin.getline(message, 100);
cout << "Enter key: ";
cin >> key;
for(i = 0; message[i] != '\0'; ++i){
ch = message[i];
if(ch >= 'a' && ch <= 'z'){
ch = ch + key;
if(ch > 'z'){
ch = ch - 'z' + 'a' - 1;
}
message[i] = ch;
}
else if(ch >= 'A' && ch <= 'Z'){
ch = ch + key;
if(ch > 'Z'){
ch = ch - 'Z' + 'A' - 1;
}
message[i] = ch;
}
}
cout << "Encrypted message: " << message;
return 0;
}
运行正常。
我运行它,它给了我
Enter a message to encrypt:
让我说我决定输入:
Hello hi
输入后,接下来它将给您:
Enter key:
让我输入:
1
输入后,它将给我:
Encrypted message: Ifmmp ij
这是我所期望的,它工作正常,将邮件移了1个字母。
但是,当我将其包含在其余代码中时,就是我遇到了问题。
这是我到目前为止拥有的所有代码:
main.cpp
#include <iostream>
#include "E.h"
using namespace std;
int main()
{
char eord;
cout << "Encrypt or Decrypt?" << "\n" << "Press E for Encrypt or press D for Decrypt" << endl;
cin >> eord;
switch (eord)
{
case 'E':
cout << "Encryption" << endl;
Encryption();
break;
case 'D':
cout << "Decryption" << endl;
break;
default:
cout << "ERROR: Invalid response";
}
system("pause");
return 0;
}
E.h
#ifndef E_H
#define E_H
int Encryption();
#endif
E.cpp
#include<iostream>
using namespace std;
int Encryption()
{
char message[100], ch;
int i, key;
cout << "Enter a message to encrypt: "<<endl;
cin.getline(message, 100);
cout << "Enter key: ";
cin >> key;
for (i = 0; message[i] != '\0'; ++i) {
ch = message[i];
if (ch >= 'a' && ch <= 'z') {
ch = ch + key;
if (ch > 'z') {
ch = ch - 'z' + 'a' - 1;
}
message[i] = ch;
}
else if (ch >= 'A' && ch <= 'Z') {
ch = ch + key;
if (ch > 'Z') {
ch = ch - 'Z' + 'A' - 1;
}
message[i] = ch;
}
}
cout << "Encrypted message: " << message;
return 0;
}
当我尝试运行此程序时,我一下子就明白了:
Enter a message to encrypt: Enter key:
它跳过getline,甚至不让我输入所需的消息,我在做什么错?就其自身而言,E.cpp运行良好,但其他情况则不行