函数encrypt将一个字符串引用作为参数,并通过将字符串中的每一个值加1来改变其值。函数decrypt将字符串引用作为参数,并通过将字符串中的每一个值减1来改变其值。函数main调用函数encrypt和decrypt,并将加密字符串和解密字符串打印出来,如实例输出中所示。
实例输出
Encrypt string is:uijt!jt!b!tfdsfu”
Decrypt string is:this is a secret!
参考程序模板:
#include <iostream>
using namespace std;
/* write the prototype for function encrypt */
/* write the prototype for function decrypt */
int main()
{
// Initialize an input string
string s = "this is a secret!";
encrypt( s );
cout << "Encrypt string is:" << s << "\n";
decrypt( s );
cout << "Decrypt string is:" << s << endl;
return 0;
}
void encrypt( string &e )
{
/* write implementation for function encrypt */
}
void decrypt( string &e )
{
/* write implementation for function decrypt */
}
#include<iostream.h>
#include<string.h>
void main()
{
char str[100];
int n,c,i;
cout<<"请输入字符串:"<<endl;
cin >> str;
cout<<"请输入密钥:"<<endl;
cin >>n;
cout<<"如果需要加密,请输入1"<<endl;
cout<<"如果需要解密,请输入2"<<endl;
cin>>c;
if(c==1)
{
for(i=0;i<strlen(str);i++)
{
str[i]+= n;
if(str[i]>'z'||(str[i]>'Z'&&str[i]<'a'))
str[i]-= ('z'-'a')+1;
}
cout<<str<<endl;
}
else if(c==2)
{
for(i=0;i<strlen(str);i++)
{
str[i]-= n;
if(str[i]<'A'||(str[i]>'Z'&&str[i]<'a'))
str[i]+= ('z'-'a')+1;
}
cout<<str<<endl;
}
}