0

I have debugged my program throughout and it compiles perfectly. The issue I have though is the it doesn't give me the output I expected. Im creating a vigenere cipher in c and im pretty sure that you all know what its suppose to do. Heres the error :

When I type in the key bacon as a command line argument and the message i want to deliver is Meet me at the park at eleven am, I should get Negh zf av huf pcfx bt gzrwep oz. Instead what i get is

enter image description here

I don't know why this is occuring but here's my code below, and if someone can just give me a hint on how to fix the problem then I would really appreciate it.

Thank you, Shayan.

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

int main (int argc, string argv[]) 

{

 string plaintext = GetString(); 
 int plaintext_length = strlen(plaintext); 
 string key = argv[1];
 int key_length = strlen(key); 
 int shift[key_length]; 

    if (argc != 2) {

        printf("The command is not valid and cannot be used as a key to encrypt your message\n");
        return 1; 
    }



    for (int i = 0; i < key_length; i++) 

    {

        if (!isalpha(key[i])) 

        {
            printf("The command is not valid and cannot be used as a key to encrypt your message\n");
            return 1; 
        }

    } 



    for (int i = 0; i < key_length; i++) 

    {
        if (isupper(key[i])) {

            shift[i] = key[i] - 65; 

        } else {

           shift[i] = key[i] - 97;       
    } 

}   


    for (int j = 0, i = 0; j < plaintext_length; j++) 

    { 

        if (islower(plaintext[j])) 
        { 
            printf("%c", (plaintext[j] + shift[i]) % 26); 

        }   else if (isupper(plaintext[j])) 

            {
                printf("%c", (plaintext[j] + shift[i]) % 26);
            }


        }

        printf("\n"); 
        return 0;

    }

1 Answer 1

1

printf("%c", (plaintext[j] + shift[i]) % 26); The modulo function depends on the letters being represented as a number from 0 to 25 inclusive, but letters are represented in a computer as ASCII values. Let's take an example. Say you have A. Then A % 26 = 65 % 26 = 13. ASCII 13 is a carriage return. You need to first convert from ASCII to something from 0 to 25, for both the key and the letter to encode.

Next, even though you are identifying whether the letter to encode is upper or lower case, you are doing exactly the same thing to each.

Finally, keep in mind that chars act just like 1 byte signed ints. If you do math on them and they go above 127, the results can be unpredictable.

This will get you going. If this answers your question, please click on the check box to accept it.

You must log in to answer this question.

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