I am a beginner trying to learn to code. Currently I am doing the CS50 course. I have encountered a problem with the Vigenere cipher problem; please see my code on a github link below.
#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ASCII_VALUE_LOWER 97
#define ASCII_VALUE_UPPER 65
#define NR_OF_LETTERS 26
int main(int argc, string argv[])
{
char key[strlen(argv[1]) + 1];
strcpy(key, argv[1]);
int keyLen = strlen(key);
for (int k = 0; k < keyLen; k++)
{
if (!isalpha(key[k]))
{
printf("ERROR: Secret key has to be alphabetical string, program will be terminated now!\n");
return 1; // main should return 1 (signify an error)
}
//converting key letters to respective values
if (isupper(key[k]))
{
key[k] -= ASCII_VALUE_UPPER;
}
key[k] -= ASCII_VALUE_LOWER;
}
//if program is executed without an argument, or with more than one arguments
if (argc != 2)
{
printf("ERROR: You need to give a secret key as an argument, program will be terminated now!\n");
return 1; // main should return 1 (signify an error)
}
else
{
string plaintext = get_string("plaintext: "); //get a plaintext from a user using cs50 custom function from their library
int stringLen = strlen(plaintext);
int keyIndex = 0;
for (int j = 0; j < keyLen; j++)
{
}
//for each character in the plaintext string
for (int i = 0; i < stringLen; i++)
{
//check if is alphabetic (tolower, toupper)
if (isalpha(plaintext[i]))
{
//cypher_character = (plain_character + key_character)% 26
if (islower(plaintext[i]))
{
keyIndex %= keyLen;
plaintext[i] = ((plaintext[i] - ASCII_VALUE_LOWER + key[keyIndex]) % NR_OF_LETTERS) + ASCII_VALUE_LOWER;
}
else
{
plaintext[i] = ((plaintext[i] - ASCII_VALUE_UPPER + key[keyIndex]) % NR_OF_LETTERS) + ASCII_VALUE_UPPER;
}
keyIndex++;
}
//else leave as is
}
//print ciphertext in a format "ciphertext: " + ciper
printf("ciphertext: %s\n", plaintext);
return 0;
}
}
The issues are as following:
if you pass an argument in uppercase letters in a key, the values are weird and the conversion doesn't work. The idea is to take each character in a string key and subtracting 65 if uppercase, or 97 if lowercase, so their ASCII value would go to 0 - 25. I then can make a use of them in a Vigenere cipher formula:
cipher[i_index] = (plaintext[i_index] + key[j_index]) % 26
doesn't handle lack of
argv[1]
, even though there is an IF condition(!argc == 2)
, so it shouldn't go through if you don't pass anything."failed to execute program due to segmentation fault".
I have tried everything in my capability, I am pretty tired, maybe tomorrow the solution will popout instantly. I ask you to give me some hints, possibly not revealing everything, but maybe guiding me, so I can learn from it.