Skip to main content
3 of 5
added 313 characters in body
MARS
  • 5.2k
  • 3
  • 14
  • 23

Vigenere cipher

Here is my code. Please help me where am I wrong?

Firstly I'm including next libraries:

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <stdlib.h> //for converting argv to int
#include <ctype.h> //for isalpha function


int main (int argc, string argv[])  
{
    if (argc != 2)
    {
        printf("missing the key\n");
        return 1;
    }
    
    char* key = argv[1];
    
    if (!isalpha(key[0]))
    {
        printf("key should be the alphabetical\n");
        return 1;
    }
    
    char* s = GetString();
    int j;

    for (j = 0; j < strlen(s); j++) //qty of chars in string
            {
                j = j % strlen(key); //to loop the key word through string
            }
    
    if (s != NULL)
    {
        for (int i = 0; i < strlen(s); i++) 
            {
                if (isalpha(s[i])) //if chars are alphabet
                {
                    if (islower (s[i])) //if alpabet chars is lowerc
                    {
                         if (s[i] + key[j] > 122)
                         {
                             s[i] = s[i] - 26;
                         }
                    printf("%c", s[i] + key[j]);
                    }
                
                    else if (isupper (s[i])) //if alpabet chars is uppercase
                    {
                         if (s[i] + key[j] > 90)
                         {
                             s[i] = s[i] - 26;
                         }
                    printf("%c", s[i] + key[j]);
                    }
                }
                else
                {
                    printf("%c", s[i]);
                }
            }
        printf("\n");  
    }
    return 0;
}