凯撒密码输出空白行

时间:2018-01-14 01:05:27

标签: c cs50 caesar-cipher

我正在从CS50课程中解决问题,我们必须实施Caesar的密码。以下代码仅适用于数字(它们与预期保持一致),当您输入一个字符时,不会输出任何内容。怎么了?

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
//problem set requires arguments
int main (int argc, string argv [])
{
    int i = 0;

    if (argc != 2){
        printf ("Retry\n");
        return 1;
    } else {
        int x = atoi(argv [1]);
        //gets plaintext
        string a = get_string ("plaintext:");
        printf("ciphertext:");
        for (i = 0; i <= strlen(a); i++){
            //if character is a number it remains unchanged
            if (isdigit(a[i])){
                printf ("%c", a[i]);
            } else {
                if (isupper(a[i])){
                    //converts from ASCII index to alphabetical index
                    char y = a[i] - 65;
                    //Caesar cipher formula. If upper case remains upper case.
                    y = toupper(a[i] + x % 26);
                    //goes back ASCII
                    printf("%c", y + 65);
                    } else if (islower(a[i])){
                    //converts from ASCII index to alphabetical index
                    char t = a[i] - 65;
                    //Caesar cipher formula. If lower case remains lower case.
                    t = tolower(a[i] + x % 26);
                    //goes back to ASCII
                    printf("%c", t + 65);
                    }
                }
           }
        }
}

1 个答案:

答案 0 :(得分:1)

65是字母'A'的ASCII值。如果您正在处理小写字词,则需要97,这是'a'

的ASCII值

您已计算t,但未将结果带到下一行。而且,你必须在整个线上取模数。您希望t介于026之间,然后将其添加到97

char t = a[i] - 97;
t = (t + x) % 26;
printf("%c", t + 97);

for循环也应该达到strlen(a)。字符串a中的最后一个索引是空字符,不应修改它。您也可以在此处使用'a'代替97

for(i = 0; i < strlen(a); i++)
{
    if(isupper(a[i]))   
    {
        char y = a[i] - 'A';
        y = (y + x ) % 26;
        printf("%c", y + 'A');
    }
    else if(islower(a[i])) 
    {
        char t = a[i] - 'a';
        t = (t + x )% 26;
        printf("%c", t + 'a');
    }
    else 
    {
        printf("%c", a[i]);
    }
}