I prematurely submitted my code without including the if() statements that check if the second command line argument was a digit (if not it would produce an error message). My code was running perfectly fine before I remembered to add this section in, and it got all smileys. But I noticed I hadn't included it and, because I want to actually fulfill all criteria of the project, I added it in afterwards and it seems to be the source of the problem as my code is now giving me Segmentation Fault warnings when I try to run it. If anyone could tell me why this is, I'd be grateful as I'm well and truly stumped.
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h> //CAESAR.C, scroll to bottom to see full summary, not the "alphabet" arrays just below as you do
const char upperalphabet[26] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
const char loweralphabet[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
int main(int argc, string argv[]) //the key will be inputted through a command line argument
{
//below are terms in which the user's input (for the "key") may be rejected as invalid
if (argc != 2)
{
printf("Error: please limit input to 1 other command-line argument!");
return 1;
}
else if (argv[1] <= 0)
{
printf("Error: please provide a positive integer!");
return 1;
}
// new code causing problems from here//
int key;
if (isdigit(argv[1]))
{
key = atoi(argv[1]);
}
else
{
printf("Usage: ./caesar key");
return 1;
}
//to here//
string plaintext = get_string("plaintext: ");
printf("\n ciphertext: ");
for (int n = 0; n < strlen(plaintext); n++)
{
/*Running through the string, if a char isn't an alpha-char, it's printed as is, if it is
an alpha-char, it'll be sorted by its lettercase*/
if (isalpha(plaintext[n]))
{
if (isupper(plaintext[n]))
{
int z;
for (z = 0; plaintext[n] != upperalphabet[z]; z++)
;
/*above is a for-loop with nothing to implement, it simply increments the alphabet array through z until plaintext's char matches
the present element in the alphabet array*/
int ciphernumber = ((z + key) % 26);
printf("%c", upperalphabet[ciphernumber]);
}
else if (islower(plaintext[n])) //code here is same as above, just for lowercase array
{
int z;
for (z = 0; plaintext[n] != loweralphabet[z]; z++)
;
int ciphernumber = ((z + key) % 26);
printf("%c", loweralphabet[ciphernumber]);
}
}
else
{
printf("%c", plaintext[n]); //non-alphabetical plaintext array elements get printed here
}
}
printf("\n");
return 0;
}