简体   繁体   English

cs50 中的 Vigenere 密码

[英]Vigenere cipher in cs50

I'm working my way through an online class teaching me how to code.我正在通过在线课程教我如何编码。 I'm very new to this and have been slowly making my way through this class.我对此很陌生,并且一直在慢慢地通过这门课。 I've run into an issue with the vingenere cipher.我遇到了 vingenere 密码的问题。 It doesn't iterate the key through the whole input.它不会在整个输入中迭代键。

Edit: the key should iterate through the user input and when it reaches the end of the key, loop back and begin again.编辑:键应该遍历用户输入,当它到达键的末尾时,循环返回并重新开始。 The key should also skip over any special character(!@#" ",etc)键还应跳过任何特殊字符(!@#" "等)

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

int main (int argc, string argv[])
{
    if(argc !=2)
    {
        printf("please put in command line argument: example - ./vigenere command\n");
        return 1;
    }
    string key = argv[1];
    int keylength = strlen(key);
    for (int i=0;i<keylength; i++)
    {
        if(!isalpha(key[i]))
        {
            printf("please make sure command is letter only. Please no numbers or special characters!\n");
            return 1;
        }
    }
    string input = GetString();

    for (int i=0, k=0; i<keylength; i++)
    {
        if(isalpha(input[i]))
        {
            if(isupper(input[i]))
            {
                input[i]=((input[i]-'A')+(key[k%keylength]))%26+'A';
            }
            else
            {
                if(islower(input[i]))
                {
                input[i]=((input[i]-'a')+(key[k%keylength]))%26+'a';
            }
        }
    }
}
printf("%s\n",input);
return 0;
}

I know string is not normal, but it's included in the header to help with new students.我知道字符串不正常,但它包含在标题中以帮助新学生。 I guess we learn more as the class progresses.我想随着课程的进行,我们会学到更多。

You didn't change k in your for loop.您没有在for循环中更改k And indeed I don't think you need k at all.事实上,我认为你根本不需要k And your loop only iterate through the length of key instead of the length of input .并且您的循环仅遍历key的长度而不是input的长度。

int inputlength = strlen(input);
for (int i = 0; i < inputlength; ++i) {
    if (isupper(input[i]))
        input[i] = ((input[i]-'A') + (key[i%keylength])) % 26 + 'A';
    /* ...                                ^ Use i here */
}

Regarding the issue that when the key is b and input is A , you must adjust the key.关于key为b ,input为A ,必须调整key的问题。

input[i] = ((input[i]-'A') + (key[i%keylength]-'a')) % 26 + 'A';

To skip input special characters,要跳过输入特殊字符,

int inputlength = strlen(input);
for (int i = 0, k = 0; i < inputlength; ++i) {
    if (isupper(input[i]))
        input[i] = ((input[i]-'A') + (key[(k++)%keylength])) % 26 + 'A';
    /* ...                                 ^^^ */
    else if (islower(input[i]))
        input[i] = ((input[i]-'a') + (key[(k++)%keylength])) % 26 + 'a';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM