/*
* @Author: jjk
* @Date: 2019-06-03 21:31:04
* @Last Modified by: jjk
* @Last Modified time: 2019-06-10 16:05:42
* 程序功能:
* 字符串的加密和解密:
* 愷撒密碼是古羅馬愷撒大帝用來對軍事情報進行加解密的算法,
它採用了替換方法對信息中的每一個英文字符循環替換爲字母表序列中該字符後面的第三個字符,
* 即,字母表的對應關係如下:
原文: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
密文:D E F G H I J K L M N O P Q R S T U V W X Y Z A B C
對於原文字符P,其密文字符C滿足如下條件:C=(P+3) mod 26
上述是凱撒密碼的加密方法,解密方法反之,即:P=(C-3) mod 26
假設用戶可能使用的輸入包含大小寫字母a~zA~Z、空格和特殊符號,
請編寫一個程序,對輸入字符串進行愷撒密碼加密,直接輸出結果,其中空格不用進行加密處理。使用input()獲得輸入。
*
* 思路:
1、while無線循環,聲明兩個字符數組:保存明文和密文
2、首次用戶輸入字符串,進行明文加密成密文操作
3、之後用戶輸入命令字符實現判斷:輸入:“1”加密新的明文,輸入:“2”對“明文”反向解密,輸入:“3” 退出
*
*
*
*
*
*/#include<stdio.h>// A=65,Z=90,a=97,z=122// 加密voidCaesarEncrypt(char*pstrBff,int nKey)// nKry:偏移量{int count;for(count =0; pstrBff[count]!='\0'; count++){if((pstrBff[count]>='A'&& pstrBff[count]<='Z')||(pstrBff[count]>='a'&& pstrBff[count]<='z')){
pstrBff[count]+= nKey;if(pstrBff[count]>'Z'&& pstrBff[count]<'a')
pstrBff[count]-=26;// -26elseif(pstrBff[count]>'z')
pstrBff[count]-=26;}}}// 解密voidCaesarDecrypt(char*pstrBff,int nKey){int count;for(count =0; pstrBff[count]!='\0'; count++){if((pstrBff[count]>='A'&& pstrBff[count]<='Z')||(pstrBff[count]>='a'&& pstrBff[count]<='z')){
pstrBff[count]-= nKey;if(pstrBff[count]<'A')
pstrBff[count]+=26;elseif(pstrBff[count]>'Z'&& pstrBff[count]<'a')
pstrBff[count]+=26;}}}intmain(void){char strBff[100];// 原文int bExit =0;// 標識符unsignedint nSel, nKey =0;printf("“1”加密新的明文,輸入:“2”對剛加密的密文進行解密,輸入:“3”退出");while(!bExit){printf("\n**************************\n");printf("請輸入指令:");scanf("%d",&nSel);while(getchar()!='\n');switch(nSel){case1:printf("請輸入要加密的明文:");gets(strBff);printf("請輸入偏移量:");scanf("%d",&nKey);// 偏移量while(getchar()!='\n');CaesarEncrypt(strBff, nKey);// 加密printf("加密後的密文是: %s\n", strBff);break;case2:printf("請輸入需要解密的明文:");gets(strBff);printf("請輸入偏移量:");scanf("%d",&nKey);// 偏移量while(getchar()!='\n');CaesarDecrypt(strBff, nKey);//解碼printf("解碼後的明文:%s\n", strBff);break;case3:return1;default:printf(".\n");}}return0;}