总体概览:先建立KEY和PWD两个密码表,用于大小写转换。Encryption加密函数,Decryption解密函数。加密解密过程中,将每一个字符都先转为int类型,进行判断是否属于大小写字母。之后把下标规定范围为0到25,并使用密码表内的字符进行相应的赋值。read_class函数用去读取文件,write_class函数用于写入文件。
这里变量的命名不太规范,忽略就好QAQ。
要求:利用编程技能实现凯撒密码
读取写入文件需要读入空格问题
#include
using namespace std;
#define _ ios_base::sync_with_stdio(0),cin.tie(0)
char KEY[26]={'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 PWD[26]={'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'};
string str;
void Encryption (int n);
void Decryption (int n);
int read_class();
void write_class();
int main()
{
_;
int length;
int flag;
while(true)
{
cout<<"请输入你的操作:"<<endl;
cout<<"1---读取字符串"<<endl<<"2---写入字符串"<<endl<<"3---加密"<<endl<<"4---解密"<<endl<<"5---退出"<<endl;
cin>>flag;
if(flag == 1)
{
length = read_class();
}
else if(flag==3)
Encryption(length);
else if(flag ==4)
Decryption(length);
else if(flag==5)
break;
else if(flag==2)
write_class();
else
cout<<"输入错误,请重新输入!"<<endl;
}
return EXIT_SUCCESS;
}
//加密
void Encryption (int n)
{
int index;
for(int i=0;i<n;i++)
{
index = (int)str[i];
if(str[i]>='a'&&str[i]<='z')
{
index -=(int)'a';
index +=3;
if(index >= 26)
index-=26;
str[i] = PWD[index];
}else if(str[i]>='A'&&str[i]<='Z')
{
index -=(int)'A';
index -=2;
if(index < 0)
index +=26;
str[i] = KEY[index];
}
}
cout<<"加密成功"<<endl;
cout<<str<<endl;
}
//解密
void Decryption (int n)
{
int index;
for(int i=0;i<n;i++)
{
index = (int)str[i];
if(str[i]>='A'&&str[i]<='Z')
{
index -=(int)'A';
index -=3;
if(index < 0)
index +=26;
str[i] = KEY[index];
}else if(str[i]>='a'&&str[i]<='z')
{
index -=(int)'a';
index +=2;
if(index >= 26)
index -=26;
str[i] = PWD[index];
}
}
cout<<"解密成功"<<endl;
cout<<str<<endl;
}
//读入
int read_class()
{
ifstream f;
f.open("passwd.txt");
while(getline(f,str))
cout<<str<<endl;
f.close();
int i=(int)str.length();
cout<<"读取成功!"<<endl;
return i;
}
//写入
void write_class()
{
fstream f;
f.open("passwd.txt",ios::app);
f<<str<<endl;
f.close();
cout<<"写入成功!"<<endl;
}