c中的凯撒密码

时间:2015-03-31 00:01:19

标签: c caesar-cipher

我一直在研究这个Caesar密码,这是我到目前为止所得到的,当程序运行时没有任何事情发生。

#include <stdio.h>
#define MAX 80

 main()
{
    int shift, num; 
    char ciph[MAX];
    printf("Enter the message to be encrypted: ");
    while ((ciph[num] = getchar()) != '\n'){  //loops until a blank space is read
        for(num=0; num<MAX; num++){ //scans characters into the array
        ciph[num] = getchar();
        }
    }
    printf("\nEnter the shift amout: ");
    scanf("%d", &shift); //reads the shift amount
    for (num = 0; num < MAX; num++) //shifts the letter
    {
        int c = ciph[num];
        if ('a' >= c && c <= 'z')
            c = ((c - 'a') + shift) % 26 + 'a';
        else if ('A' >= c && c <= 'Z')
            c = ((c - 'A') + shift) % 26 + 'A';
        else
        {

    }
    ciph[num] = c;
}
printf("%c", ciph[num]); //prints the encryption
}

2 个答案:

答案 0 :(得分:0)

我不确定你的意图是什么,但是

'a' <= ciph

需要

'a' <= ciph[SOMETHING]

ciph = (ciph - 'a')+shift) % 26 + 'a';

缺少一个&#39;(&#39;

答案 1 :(得分:0)

我认为你应该留下这个空白的空白,但我想这取决于你。

//read the whole line

int i;
int len = strlen(line);
for (i = 0; i < len; i++)
{
    int c = line[i];
    if ('a' >= c && c <= 'z')
        c = ((c - 'a') + shift) % 26 + 'a';
    else if ('A' >= c && c <= 'Z')
        c = ((c - 'A') + shift) % 26 + 'A';
    else
    {
        //leave it
    }
    line[i] = c;
}

//write the whole line