1. C語言 字元串加密
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
intmain(void)
{
charc[100];
intk;
intlen,i,temp;
scanf("%s",c);
scanf("%d",&k);
len=(int)strlen(c);
k=k%26;
for(i=0;i<len;i++)
{
if(c[i]>='a'&&c[i]<='z')
{
if(c[i]+k>'z')
{
temp='z'-c[i];
temp=k-temp-1;
c[i]='a'+temp;
}
else
{
c[i]+=k;
}
}
elseif(c[i]>='A'&&c[i]<='Z')
{
if(c[i]+k>'Z')
{
temp='Z'-c[i];
temp=k-temp-1;
c[i]='A'+temp;
}
else
{
c[i]+=k;
}
}
else
{
/*donothing*/
}
}
printf("%s ",c);
return0;
}
2. C語言英文文本加密
#include "stdio.h"
#include <stdlib.h>
int main(int argc,char *argv[]){
FILE *fp,*fq;
int k,t;
fp=fopen("AAA12345678901.txt","w+");
if(!fp || (fq=fopen("tmp.txt","w"))==NULL){
printf("Failed to open the file and exit... ");
return 0;
}
printf("Please enter a short passage(letters+space+punctuation,'Enter' end)... ");
while((t=getchar())!=' ')//為文件輸入內容
fputc(t,fp);
printf("Please enter the encryption key(int >0)... k=");
while(scanf("%d",&k)!=1 || k<1){//輸入加密密鑰並判斷是否正確
printf("Input error, redo: ");
fflush(stdin);
}
rewind(fp);
while(t=fgetc(fp),!feof(fp))//加密
if(t>='A' && t<='Z')
fputc(((t-'A')+k)%26+'A',fq);
else if(t>='a' && t<='z')
fputc(((t-'a')+k)%26+'a',fq);
else
fputc(t,fq);
fclose(fp);//關閉原文件
fclose(fq);//關閉加密後的文件
remove("AAA12345678901.txt");//刪除原文件
rename("tmp.txt","AAA12345678901.txt");//將加密後的文件更換為原文件名
printf(" ");
if(fp=fopen("AAA12345678901.txt","r")){
while((t=fgetc(fp))!=EOF)
printf("%c",t);
printf(" Encryption success! ");
}
else
printf(" Failed to open the encrypted file... ");
fclose(fp);
return 0;
}
代碼格式和運行樣例圖片:
3. c語言字母加密
按照你的要求編寫的字母加密的C語言程序如下
(姓字母向後移兩位,名字母向後移三位)
#include<stdio.h>
#include<string.h>
int main(){
char src[30],result[]="",ch[2]={'