CS50 - pset2 - Vigenere

时间:2016-02-25 14:21:18

标签: vigenere

我目前正在努力使用pset2,尤其是使用vigenere。

这是我的代码:

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

int main (int argc, string argv[])
{

    //Assess the fact that there is only 1 command line argument
    if(argc != 2)
    {
        printf("You should only have 1 command line argument !\n") ;
        return 1 ;
    }

    string k = argv[1] ;
    int klength = strlen(k) ;

    for(int i = 0; i < klength; i++)
    {
        if(!isalpha(k[i]))
        {
            printf("Please make sure the argument is only composed of alphabetical characters\n") ;
            return 1 ;
        }
    }

    //Get the text to be crypted
    string s = GetString() ;
    int slength = strlen(s) ;

    //Deliver the crypted text
    for( int i = 0, j = 0 ; i < slength ; i++)
    {
        int kindex = j % klength ;

        if(isalpha(s[i]))
        {
            if(isupper(s[i]))
            {
                if(isupper(k[kindex]))
                {
                    int crypt = (((s[i] - 'A') + (k[kindex] - 'A') % 26)) + 'A' ;
                    printf("%c", crypt ) ;
                }
                else
                {
                    int crypt = (((s[i] - 'A') + (k[kindex] - 'a')) % 26) + 'A' ;
                    printf("%c", crypt ) ;
                }
            }
            if(islower(s[i]))
            {
                if(isupper(k[kindex]))
                {
                    int crypt = (((s[i] - 'a') + (k[kindex] - 'A')) % 26) + 'a' ;
                    printf("%c", crypt) ;
                }
                else
                {
                    int crypt = (((s[i] - 'a') + (k[kindex] - 'a')) % 26) + 'a' ;
                    printf("%c", crypt ) ;
                }
            }
        j++ ;
        }
        else
        {
            printf("%c" , s[i]) ;
        }
    }

    printf("\n") ;
    return 0 ;
}  

使用check50,这是我收到的错误:

:(使用“BaZ”作为关键字将“BaRFoo”加密为“CaQGon”    \预期输出,但不是“CakGon \ n” :(使用“BAZ”作为关键字将“BARFOO”加密为“CAQGON”    预期输出,但不是“CAkGOh \ n”

这是我的沙箱:sandbox 我不明白为什么两个输出不一样(cakgon vs cakoh)以及为什么它与预期不同。问题可能在于“//提供加密测试”部分。

我花了几个小时试图弄清楚它没有成功。

提前感谢任何帮助/提示/建议。

巴普蒂斯特

1 个答案:

答案 0 :(得分:0)

我终于明白了。 其中一个&#34;%26&#34;

之前缺少括号
相关问题