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

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

    if (argc != 2)
    {
        printf("Please give one command line argument\n");
    }

   for (int i = 0, n = strlen(k); i < n; i++)
   {
       if (! isalpha(k[i]))
       printf("Please give command line argument of alphabets\n");
   }

   printf("Give a string to be encrypted in vigenere cipher\n");
   string plaintext = GetString();

   for (int i = 0, n = strlen(plaintext); i < n; i++)
   {
       if(isupper(plaintext[i]))
       {
           if(isupper(k[i % strlen(k)]))
           {
               printf("%c",((((plaintext[i] + (k[i % strlen(k)] - 'A')) - 'A') %26) + 'A'));
           }
           if(islower(k[i % strlen(k)]))
           {
               printf("%c",((((plaintext[i] + (k[i % strlen(k)] - 'a')) - 'A') %26) + 'A'));
           }
       }


       else if(islower(plaintext[i]))
       {
           if(isupper(k[i % strlen(k)]))
           {
               printf("%c",((((plaintext[i] + (k[i % strlen(k)] - 'A')) - 'a') %26) + 'a'));
           }
           if(islower(k[i % strlen(k)]))
           {
               printf("%c",((((plaintext[i] + (k[i % strlen(k)] - 'a')) - 'a') %26) + 'a'));
           }
       }

       else
       {
           printf("%c",plaintext[i]);
       }
   }
   printf("\n");
}
1

This is probably the most common error for this program. The index for the plain text string, i, cannot be used as the index for the key string. While the plaintext index must be incremented for every character, the index for the key string can only be indexed when an alpha is processed, and never when a non-alpha is processed! Therefore, the key index must be independent and unrelated to the plain text index.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Thanks, I got my mistake. Will try to fix this! :) Jan 6 '17 at 10:58

You must log in to answer this question.

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