Vigenere cs50 Pset2末尾的多余字符

时间:2019-05-13 23:39:39

标签: c cs50 vigenere

我是编码的新手,已经做了两周了。我现在正在参加CS50课程,并且已经为pset2 vigenere编写了代码。当我使用check50时,我意识到它希望我在不跳过键的情况下考虑空格和非字母。

我添加了“ j--;”并且,尽管代码是正确的,但现在它在密文末尾创建了额外的随机字符。

另外,当在我的代码中检查argv [1]中的字母时,我有一个if语句,其中包含“ int key = argv [1] [i];”。在身体里。它什么也没做,但是我不知道如何让它继续检查下一个字符而没有空的身体,这是不允许的。

任何帮助将不胜感激!非常感谢你!

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


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

{
    //making sure it is not more than one command line
    if (argc != 2)
    {
        printf("Usage: ./vigenere key \n");
        return 1;
    }

    //if it is one command line, making sure the input is just letters      
    if (argc == 2)
    {
        for (int i = 0, n = strlen(argv[1]); i < n; i++)
        {
            if (isalpha(argv[1][i]))
            {    
                int key = argv[1][i];
            }
            else
            {
                printf("Usage: ./vigenere key \n");
                return 1;
            }
        }   

    }
    //asking user for input text
    string plaintext = get_string("plaintext: ");
    printf("ciphertext:");

    //going through a loop to turn plain text into ciphertext 
    int i = 0; 
    int n = strlen(plaintext); 
    string key = argv[1];


    //looping through the key    
    while (i < n)

    {

        for (int j = 0, m= strlen(key); j < m; j++, i++)

        {   
            //using the asci of each char as an int
            int asc = (plaintext[i]);
            int k = key[j];
            //if lowercase
            if (k >= 97 && k <= 122)
            {
                k -= 97;
            }
            else
            {
                k -= 65;
            }

            //if lowercase
            if (asc >= 97 && asc <= 122)
            {
                printf("%c", ((((asc - 97) + k) % 26) + 97));
            }
            //if uppercase
            else
            {
                if (asc >= 65 && asc <= 90)
                {
                    printf("%c", ((((asc - 65) + k) % 26) + 65));
                }
                //if non-letter
                else
                {  
                    printf("%c", asc);
                    j--;

                }
            }

        }  


    }


    printf("\n");

}      

这些是预期结果与实际结果:

key: baz
plaintext: hello, world!
expected ciphertext: iekmo, vprke!

actual ciphertext:   iekmo, vprke!!pu

1 个答案:

答案 0 :(得分:2)

由于程序在Attribute value must be constanti递增,因此它允许读取明文末尾的内容。在for循环完成之前,while循环将不评估for (int j = 0, m= strlen(key); j < m; j++, i++)。这有可能导致无限循环,具体取决于明文结尾之后的内存内容。如果它从未遇到a-z或A-Z范围内的物体,它将永远i

如果j--,则需要打破for循环。

相关问题