void encryp(char *plain,char *cipher)这个函数你写复杂了,如下就可以了——
void encryp(char *plain,char *cipher){
int i;
for(i=0;plain[i];i++)
cipher[i]=plain[i]-24;
cipher[i]='\0';
}
这样加密就完结了。
#include stdio.h
#include ctype.h
char *encrypt(char *text) {
char c;
char *p = text;
for (; *text; ++text) {
c = *text;
if (isdigit(c))
*text = '0' + '9' - c;
else if (islower(c)) {
c = c + 3;
if (c 'z')
c = c - 26;
*text = c;
} else if (isupper(c)) {
c = c + 3;
if (c 'Z')
c = c - 26;
*text = c;
}
}
return p;
}
int main() {
char text[100];
printf("输入明文:");
scanf("%s", text);
printf("密文:%s\n", encrypt(text));
getchar();
}
我尽量用注释阐述了思路,希望可以帮到你!!
#includestdio.h
#includestring.h
#define N 80 //可加密字符串最大长度
char plaintext[N]={0}; //明文,输入时输入字符,参与运算时强制转换成整数
int ciphertext[N]={0}; //密文,保存成整数,输出时强制转换成字符
int k; //后(右)移位数,相当于密钥
void getPlainText() //获得明文字符串
{
printf("请输入明文:");
scanf("%s",plaintext);
printf("\n");
}
void getLength() //获取后(右)移位数(密钥)
{
printf("请输入后移的位数:");
scanf("%d",k);
k%=26; //因为字母只有26个,所以超过26相当于重复
}
void Caesar_cipher() //凯撒加密,本程序采用的是字母循环后(右)移
{
unsigned int i;
for(i=0;istrlen(plaintext);i++)
{
//两个bool类型的变量是为了判断字符是否是字母(包括大写和小写)
bool flag1=plaintext[i]='a'plaintext[i]='z';
bool flag2=plaintext[i]='A'plaintext[i]='Z';
if(flag1||flag2){ //如果是字母,加密
ciphertext[i]=(int)plaintext[i]+k; //字母在字母表中后(右)移K位
if(ciphertext[i](int)'z'){ //保证是循环后(右)移
ciphertext[i]-=26;
}
}
else //非字母字符,不做处理,原样保存
ciphertext[i]=(int)plaintext[i];
}
}
void printCipherText() //输出加密后的密文
{
unsigned int i;
printf("\n加密后的密文是:");
for(i=0;istrlen(plaintext);i++) //把参与计算后是整数强制转换成对应的字符
printf("%c",(char)ciphertext[i]);
printf("\n");
}
void main()
{
getPlainText(); //明文
getLength(); //后(右)移位数
Caesar_cipher(); //凯撒加密
printCipherText(); //密文
}
我没注意只要小写,我写的是大小写都可以的,另外附送输入验证。
#include stdio.h
#include string.h
int main()
{
char str[]="00000",str2[]="00000",*p=str,*p2=str2;
printf("输入5个字母:");
while(*p!=0)
{
scanf("%c",p);
if(*p=='\n')
continue;
if(*p'A'||(*p'Z'*p'a') || *p'z') //输入验证,必须是字母
{
printf("只能输入字母,请重新输入\n");
p=str;
p2=str2;
fflush(stdin);//输入有错重新输入前清空缓冲区。fflush属于c扩展函数,正常使用没问题,如需在linux ggc上使用,考虑多次调用getchar函数来清空
}
else
{
*p2=(*p)+4;
if(*p290 *p297) //大写字母加4,最大位不超出
*p2='A'+(*p2-90)-1;
if(*p2122) //小写字母加4,最大位不超出
*p2='a'+(*p2-122)-1;
p2++;
p++;
}
}
printf("原字符串为:%s\n加密后的字符串为:%s\n",str,str2);
return 0;
}
C语言代码和运行结果如下:
输出符合示例,加解密均正确,望采纳~
附源码链接:字符串加解密