1.1凯撒密码

复制代码
 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 string encoder(string text,int offset)//加密 
 5 {
 6     string encoded_text=text;
 7     for(auto &i:encoded_text)
 8     {
 9         if(i>='a'&&i<='z')
10         i=(i-'a'+offset)%26+'a';
11         if(i>='A'&&i<='Z')
12         i=(i-'A'+offset)%26+'A';
13     }
14     return encoded_text;
15 }
16 string decoder(string text,int offset)//解密 
17 {
18     string decoded_text=text;
19     for(auto &i:decoded_text)
20     {
21         if(i>='a'&&i<='z')
22         i=(i-'a'-offset+26)%26+'a';
23         if(i>='A'&&i<='Z')
24         i=(i-'A'-offset+26)%26+'A';
25     }
26     return decoded_text;
27 }
28 int main()
29 {
30     string text,encoded_text,decoded_text;
31     cout<<"请输入偏移量:"<<endl;
32     int offset;//偏移量
33     cin>>offset;
34     cout << "输入英文文本: "<<endl;
35     char c=getchar();//吞掉回车 !!!!!!!!不然读入text是回车 
36     while(getline(cin,text))
37     {
38         cout<<"加密(输入:e) or 解密(输入:d) ?"<<endl;
39         char flag;
40         cin>>flag;
41         if(flag=='e')
42         {
43             encoded_text = encoder(text,offset);        
44             cout << "加密后英文文本:\t" << encoded_text << endl;
45         }
46         else
47         {
48             decoded_text = decoder(text,offset);
49             cout << "解密后英文文本:\t" << decoded_text << endl;
50         }
51         
52         cout<<"请输入偏移量:"<<endl;
53         int offset;//偏移量
54         cin>>offset;
55         cout << "输入英文文本: "<<endl;
56         char c=getchar();
57     }
58 }
复制代码

  •  注意:
    • LINE35 读入回车
    • LINE7  
      for(auto &i:encoded_text)
posted @   敲代码的喵  阅读(50)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示