0

My cipher works when the length of the key is equal to or greater than the length of the plain text. I think that the key is not repeating once the length of the plaintext exceeds the length of the key. I will post my code here and once I get an answer delete it:

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, string argv[])
{   

    // validates the key
    if (argc != 2) 
    {
        printf("You did not give the correct inputs\n");
        return 1;
    }


    // Declaring variables
    int toAscii;
    int i;



    // Converts the argv "string" into an int
    string key = argv[1];
    int keyAlpha = 0;

    //make sure key is only letters
    int check = strlen(key);
    int j;
    for(j = 0; j < check; j++)
        if (isalpha(key[j]))
        {

        }else
        {
            printf("Inputted key must only contain letters\n" );

            return 1;
        }

    // Prompted for plain text
    string prompt = GetString();
    /* Determing the string length of prompt*/
    int n = strlen(prompt);
    //int k = strlen(key);

    // It prints a new character to the length of the string

    for (i = 0; i < n; i++)
    {      
        // Checks if is in the alphabet
        if (isalpha(prompt[i]))
        {
        // Checks if it is lower case
            if (islower(prompt[i]))
            {   
                keyAlpha = (int) key[i];
                keyAlpha = keyAlpha - 97;
                toAscii = (int) prompt[i];
                toAscii = toAscii - 97; 
                // converting it to a zero indexed alpha
                toAscii = ((toAscii + keyAlpha) % 26) + 97; 
                printf("%c", (char) toAscii);
                /*if(n > k) {

                } */
             // Checks if upper case
             } else 

            {
                keyAlpha = (int) key[i];
                keyAlpha = keyAlpha - 65;
                toAscii = (int) prompt[i];
                toAscii = toAscii - 65;
                toAscii = ((toAscii + keyAlpha) % 26) + 65; 
                printf("%c", (char) toAscii);

             }
        } else 
        {
            printf("%c", prompt[i]);
        }

    }

    printf("\n");
}

1 Answer 1

2

You need 2 counters, one for the plain text and one for the key. You have the length of the key with k but you've commented it out.

Create a counter, maybe j and then increment j whenever you use it. You can use k to wrap j around (recall that if k is 5, then j%k will allow j to get to 4 and then start over at 0.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .