1

已经为此工作了很长一段时间,但似乎没有任何效果。我需要制作一个 Vigenere 密码,它将关键字作为 argy[1] 然后获取一个字符串并使用这两个,执行 Vigenere 密码所做的事情,其中​​关键字中的字母 A 和 a 对应于 0 的移位并且 z 和 Z 对应于 25 的移位。必须保留大小写(大写和小写),并且不得对字符串中的任何非字母字符进行加密,因此关键字本身中的字母不应该用完,直到下一个字母性格就在那里。这就是基本的破绽...

我将发布我的代码。请不要关注问题背后的实际数学(我可以自己弄清楚那部分),而是关注模数和我的循环的使用。现在我只处理字符串中的字符是否为小写。

该程序编译并似乎可以使用单个字母组合,而使用 argv[1] 的 'b' 和字符串 'a' 输出是 'b'。但是,两个字母关键字会产生更多的加密字母,然后是字符串中的字母(我该如何解决这个问题)。另外,当关键字用完所有字母时,我很难让关键字环绕到第一个字母(如果字符串中的字母字符比关键字多)。

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

int main(int argc, string argv[])
{
int a  = argc;    

if (a != 2)
{
    return 1;    
}

string b = argv [1]; 
int c = strlen(b);
string m;

for (int d = 0; d < c; d++)
{
    if ( isdigit(b[d]) || ispunct(b[d]) || isspace(b[d]) )
    {
        return 1;
    }
}

    m = GetString(); 

for (int i = 0, n = strlen(m); i < n; i++)
{
    if (islower(m[i]))
    {
        for (int j = 0; j <= c; j++)
        {                      
            if (j > c)                
            {
                j = 1;  
                printf("%c", ((m[i]+(b[j]))%26)+85);
            } 
            else
            {
                printf("%c", ((m[i]+(b[j]))%26)+85);
            }                                 
        }
    }
  }              
}
4

1 回答 1

2

您的问题在于我认为的密钥循环。Vingenere 密码使用输入键的每个字符来选择已旋转该键字符量的字母表(即:以该字符开头)。您正在循环数据,但对于每个数据字符,您还循环遍历所有关键字符,您应该只选择下一个字符并将键视为偏移索引的循环缓冲区。您还需要修复缩进并选择合理的变量名称。我已经附加了一个工作版本。我没有看到 typedefing const char *to的里程数string。这不是 C++。

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

int
main(int argc, char *argv[])
{
    const char *key = argv[1];
    const char *data = argv[2];
    int keylen, datalen, keyindex = 0;

    if (argc != 3) {
        fprintf(stderr, "usage: vig keystring data\n");
        return 1;
    }

    /* validate the key */
    keylen = strlen(key);
    for (int n = 0; n < keylen; n++)
    {
        if ( isdigit(key[n]) || ispunct(key[n]) || isspace(key[n]) )
        {
            fprintf(stderr, "invalid char in key at index %d\n", n);
            return 1;
        }
    }

    /* iterate over the data adding a key dependent offset*/
    datalen = strlen(data);
    for (int i = 0; i < datalen; i++)
    {
        if (islower(data[i]))
        {
            printf("%c", ((data[i] + key[keyindex]) % 26) + 85);
            /* treat key as circular buffer */
            ++keyindex;
            keyindex %= keylen;
        }
    }
    return 0;
}

测试一下:

C:\Code>vig abc abcd
aced
于 2015-07-26T10:21:48.183 回答