我的Vigenere Cypher CS50出了什么问题

时间:2016-07-06 20:39:09

标签: c vigenere cs50

CS50 pset2 Vigenere cypher的代码如下。请帮我找一下这个bug。当密钥包含字母' a'时,此代码基本上不执行任何操作。它说"浮点异常"。我不知道这意味着什么。请仔细阅读代码并告诉我这是什么错误。

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

int main(int argc, string argv[])
{
    //check if there are only two command line arguments//

    if (argc!=2)
    {
        printf("Please enter a valid input!\n");
        return 1;
    };

    string key = argv[1];

    for(int i=0, n=strlen(key); i < n; i++)
    {
        //check if there is any number in the key//

        if(!isalpha(key[i]))
        {
            printf("Invalid Key!\n");
            return 1;
        };

        //converting the key into ints.//

        if(islower(key[i]))
        {
            key[i] = key[i] - 'a';
        }
        else if(isupper(key[i]))
        {
            key[i] = key[i] - 'A';
        };
    };

    //prompt user for the string//

    string s = GetString();

    int c;
    int k;
    int stln = strlen(s);
    int kyln = strlen(key);          

    for(int j = 0, m = strlen(s); j < m; j++)
    {
        if(islower(s[j]))
        {
            s[j] = s[j] - 'a';

            //for wrapping around the key//

            if(stln > kyln)
            {
                k = j % strlen(key);
                c = (s[j] + key[k]) % 26;
                s[j] = 'a' + c;
            } 
            else
            {
                c = (s[j] + key[j]) % 26;
                s[j] = 'a' + c;
            };
         } 
         else if (isupper(s[j]))
         {
             s[j] = s[j] - 'A';

             //for wrapping around the key//

             k = j % strlen(key);

             if(stln > kyln)
             {
                 c = (s[j] + key[k]) % 26;
                 s[j] = 'A' + c;
             } 
             else
             {
                 c = (s[j] + key[j]) % 26;
                 s[j] = 'A' + c;
             };
         };

    };

    printf("%s\n", s);

};

1 个答案:

答案 0 :(得分:2)

strlen(key)在以后的代码中无效,因为之前的代码只要在使用key[]'a'时在'A'中注入空字符:

if(islower(key[i])) {
  key[i] = key[i] - 'a';

在更改其内容之前查找字符串长度key[]并使用

 int n = strlen(key);
 ...
 // k = j % strlen(key);
 k = j % n;