Okay, first time writing here and I am a complete noobie. The program compiles and I have run the debugger, and it seems that I have a segmentation fault which I have marked. Also, I have used a lot of comments to explain my logic, so please forgive me if it looks messy. Please help!!
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>
int k; // Global variable
int main(int argc, string argv[]) // We need a command line argument, and argc counts the number of
// words in input and string argv stores them
{
if (argc != 2) // we need two command line arguments so anything else should prompt the user to
// enter in the correct format,ie, ./caesar key, where key is the second
// commandline argument
{
printf("Usage: ./caesar key\n");
return 1; // Terminates the program prematurely.
}
if (argc == 2) //when the user inputs correctly
{
if (isdigit(argv[1]) == 0) // the second commandline argument that is the key, should be
// purely numeric. this checks for that. returns a boolean value,
// true / false or 1 / 0
{
printf("Usage: ./caesar key\n");// if it is false, the program is terminated with the
// message again
return 1; // same as before
}
segmentation fault starts here
if (isdigit(argv[1]) == 1) // the condition if key is numeric, which is what we want
{
k = (int) argv[1]; //stores the key
string plaintext = get_string("Plaintext: "); // Gets the plaintext from user as a string
int strlength = strlen(plaintext); // stores the length of the string as an integer
char ciphertext[strlength]; // declaring the cipher text
for (int i = 0; i <= strlength; i++) // for loop for encoding with key
{
char a = plaintext[i]; // stores the value of the i th index of plaintext, such that
// plaintext itself does not get modified as it is an array
if (isalpha(a) == 1) // sees wheter the coresponding index , now stored in a is a part
// of the alphabet, returns true if yes
{
if (isupper(a) == 1) //sees whether the index is upper case character, returns true
// if yes
{
char b = a; // storing a in b, such that a does not change
b -= 65; //converting ASCII value of block letters to Alphabetical index, ie , 0-
//25, so that they can get encrypted
b = (b + k) % 26; //encryption with key k
b += 65; //converting back to ASCII
ciphertext[i] = b; //storing encrypted index in ciphertext
}
if (islower(a) == 1) //same story as above, checking and encrypting for lower case
{
char c = a;
c -= 97;
c = (c + k) % 26;
c += 97;
ciphertext[i] = c;
}
}
if (isalpha(a) == 0) // we do not want to encrypt space or special characters like .,;@
//etc or numbers, so we us isalpha to stay clear of them
{
ciphertext[i] = a; // storing the special characters as it is.
}
}
printf("\nCiphertext: %s\n", ciphertext); //printing out ciphertext
return 0; // Command to terminate the program at the right moment
}
}
}