Задача сдвига шифра с Vigenere в C - PullRequest
0 голосов
/ 31 января 2019

Я чрезвычайно новичок в программировании, и у меня возникли некоторые трудности с Vigenere в C из курса edX CS50.Я разбил проблему на заглавные и строчные буквы и сейчас пытаюсь решить проблему только с заглавными буквами.Я использую слово «панда» в качестве моего ключа и «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 голосов
/ 31 января 2019

Требуется несколько модификаций -

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);
        }
    }
}
...