文件结构如上图
/*
作者:朱鑫
语言: C++
说明:从in.txt读取明文或者密文,经过加密或者解密后输出到
out.txt中,如果out.txt与test.txt一样则加密或者解密
成功,否则,不成功。
日期:2011/11/21
邮箱:zhuxin@nwsuaf.edu.cn
*/
#include <iostream>
#include <fstream>
using namespace std;
#define N 26
#define CRYPT_OK 1
#define CRYPT_ERROR -1
char loweralpha[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 upperalpha[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'
};
int k;
int encrypt();
int decrypt();
int main (void)
{
char choice;
//密钥
cout << "please enter k:" << endl;
cin>>k;
//必须输入E(e)或者D(d)
do
{
cout << "do you want to Encryption or Decryption:"
<< "(please enter E(e) or D(d)):" << endl;
cin >> choice;
}while (choice != 'E' && choice != 'e' && choice != 'D' && choice != 'd');
//加密
if (choice =='E' || choice == 'e')
{
cout << encrypt() << endl;
}
//解密
else if (choice == 'D' || choice == 'd')
{
cout << decrypt() << endl;
}
return 0;
}
int encrypt()
{
fstream in("in.txt",ios::in);
fstream test("test.txt",ios::in);
fstream out("out.txt",ios::out);
string str;
if(!in)
{
cerr << "can't open file!" <<endl;
}
while(!in.eof())
{
getline(in, str);
for (size_t i=0;i<str.length();i++)
{
if (isalpha(str[i]))
{
if(str[i]>='a'&&str[i]<='z')
{
if(str[i]-'a'+k > 25)
{
out << loweralpha[str[i]-'a'+k-26];
}
else
{
out << loweralpha[str[i]-'a'+k];
}
}
else
{
if(str[i]-'A'+k > 25)
{
out << upperalpha[str[i]-'A'+k-26];
}
else
{
out << upperalpha[str[i]-'A'+k];
}
}
}
else
{
out << str[i];
}
}
out << endl;
}
out.close();
out.open("out.txt", ios::in);
while( !out.eof() && !test.eof() )
{
string line1, line2;
getline(out, line1);
getline(test, line2);
if(line1 != line2)
{
return CRYPT_ERROR;
}
}
in.close();
test.close();
return CRYPT_OK;
}
int decrypt()
{
fstream in("in.txt", ios::in);
fstream test("test.txt", ios::in);
fstream out("out.txt", ios::out);
string str;
if(!in)
{
cerr << "can't open file!" << endl;
}
while(!in.eof())
{
getline(in, str);
for (size_t i=0; i<str.length(); i++)
{
if (isalpha(str[i]))
{
if (str[i] >= 'a' && str[i] <= 'z')
{
if(str[i]-'a'-k < 0)
{
out << loweralpha[str[i]-'a'-k+26];
}
else
{
out << loweralpha[str[i]-'a'-k];
}
}
else
{
if(str[i]-'A'-k < 0)
{
out << upperalpha[str[i]-'A'-k+26];
}
else
{
out << upperalpha[str[i]-'A'-k];
}
}
}
else
{
out << str[i];
}
}
out << endl;
}
out.close();
out.open("out.txt", ios::in);
while( !out.eof() && !test.eof() )
{
string line1, line2;
getline(out, line1);
getline(test, line2);
if(line1 != line2)
{
return CRYPT_ERROR;
}
}
in.close();
test.close();
return CRYPT_OK;
}