I've been trying to work through this problem for a few days but I'm stuck. I keep getting a segmentation fault whenever I run this code and I'm not sure why. Would someone be able to help me with this and also let me know if I'm on the right track as far as iterating through the key that gets entered into command line 1. I feel like I've got the right concept but at the same time it doesn't look right. Maybe I'm way off. Anyway here it is:
#include <stdio.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
//Get key from command line input at argv[1].
string k = argv[1];
//Check that the key is alphabetized and if the
command line only has two arguments. If it isn't alphabetized stop program and prompt user. If there are any more or less
than two command line arguments, stop the program and prompt user.
if (isalpha(k) == true)
{
if (argc != 2)
{
printf("Please only use one command line argument!\n");
return 1;
}
else
{
printf("Please use only an alphabetized key!\n");
return 1;
}
}
//Get text that you want to encrypt from user.
string text = GetString();
//Scrub through each letter of the text string and check to see if it is a letter or not.
If it isn't than just print it the same way that the user input it. Check letters to see if they are originally typed in upper or lower case.
//Change the letters to encrypt them by moving the current letter ahead by the number of letters indicated in the key.
for (int i = 0, j = 0, n = strlen(text); i < n; i++)
{
int KeyLength = strlen(k);
if(isalpha(text[i]))
{
if(isupper(text[i]))
{
int key = k[j % KeyLength] - 65;
printf("%c", (((text[i] + key) % 26) + 65));
j++;
}
else
{
int key = k[j % KeyLength] - 97;
printf("%c", ((text[i] + key) % 26) + 97);
j++;
}
}
else
{
printf("%c", text[i]);
}
}
printf("\n");
return 0;
}