C中Vigenere密码的转移问题

时间:2019-01-31 02:03:06

标签: c encryption cs50 vigenere

我对编程非常陌生,并且在edX课程CS50中使用Vigenere编写C语言时遇到了一些困难。我已将问题分解为大写字母和小写字母,而我现在只想解决大写字母的问题。我将“ panda”一词用作我的键,并将“ ILIKEYOU”一词用作明文。当我运行程序时,第一个字母对应于我期望的字母(23 = X)。在那之后,该程序似乎只是吐出其余7个字母的随机数。由于我的代码有很多问题,因此我没有转换回ASCII。有什么想法吗?非常感谢大家的帮助:)

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

int main(int argc, string argv[])
{
// Print error message if the user imput is executed without any 
command-line arguments or with more than one command-line argument
if (argc != 2)
{
    printf("Usage: ./vigenere k\n");
    return 1;
}

// Access key
string key = argv[1];

// Convert the array from a string to an int
int letter;
letter = atoi(argv[1]);

// Print error message if the user imput is one command-line argument 
and contains *any* non-alphabetical character(s)
for (int c = 0; c < strlen(key); c++)
{
    if (!isalpha (key[c]))
    {
        printf("Usage: ./vigenere k\n");
        return 1;
    }
 }

// Prompt the user for a string of plaintext
string p;
p = get_string("plaintext:");

//Print ciphertext
printf("ciphertext: ");

 // Accessing each character in the plaintext
for (int i = 0, n = strlen(p); i < n; i++)
{
    // Shift letters only in the plaintext
    if (isalpha(p[i]))
    {

        // Convert plaintext and key to ASCII capital letters to 
        alphabetical index
        // Encipher capital letters in plaintext and print
        int c = 0;
        if (isupper(p[i]))
        {
           printf("%i\n", ((p[i] - 65) + (toupper(key[c]) - 65)) % 26);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

需要一些修改-

int index_key = 0;
int shift= 0;
int key_len = strlen(key);
for (int i = 0, n = strlen(p); i < n; i++)
{
    // Shift letters only in the plaintext
    if (isalpha(p[i]))
    {
        // Convert plaintext and key to ASCII capital letters to 
        //alphabetical index
        // Encipher capital letters in plaintext and print
        if (isupper(p[i]))
        {
           shift = ((p[i] - 'A') + (toupper(key[index_key % key_len]) - 'A')) % 26;
           index_key++;
           printf("%c", p[i] + shift);
        }
    }
}