0

它只是行不通。你能指出什么是错的吗?当我运行它时,我得到:

jharvard@appliance (~/Dropbox/pset2): ./vigenere bacon
Meet me at the park
ARTU [R \T aW` ^NaL

这显然是错误的。我为此花费了无数个小时。这是代码:

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(int argc,string argv[])
{
    if(argc!=2)
    {
    printf("Usage: /home/cs50/pset2/caesar <key>\n");
    return 1;
    }
    else
    {
        char *k = argv[1];
        string p = GetString();
        int klen = strlen(k);

        for(int i=0; i<klen;i++)
        {
            if(isupper(k[i]))
            {
                k[i] = k[i]-65;
            }
            else if (islower(k[i]))
            {
                k[i] = k[i]-97;
            }

        }

        for(int i=0, n=strlen(p); i<n;i++)
        {

                if(isupper(p[i]))
                {
                    printf("%c", (((p[i]-65)+(k[i%klen]-65))%26)+65);
                }
                else if (islower(p[i]))
                {
                    printf("%c", (((p[i]-97)+(k[i%klen])-97)%26)+97);
                }

                else
                {
                   printf("%c", p[i]);
                }

        }
        printf("\n");

    }
}
4

1 回答 1

1

As noted in comments, the code for the loop over p should be :

EDIT per comment : code is adapted to skip non alpha charactes

int j = 0
for(int i=0, n=strlen(p); i<n;i++)
{

        if(isupper(p[i]))
        {
            printf("%c", (((p[i]-65)+(k[j%klen]))%26)+65);
            j += 1
        }
        else if (islower(p[i]))
        {
            printf("%c", (((p[i]-97)+(k[j%klen]))%26)+97);
            j += 1
        }

        else
        {
           printf("%c", p[i]);
        }
}

And the output for ./vigenere bacon with Meet me at the park should be :

Negh zf av huf pcfx
于 2014-11-05T12:47:45.973 回答