I keep getting 'Segmentation fault' every time I run the code(mentioned below). The code is compiling just fine. It's asking for input and is returning required message when the command line argument is less than 26 or if anything other than an alphabet is present. I don't know where exactly I'm going wrong.
If you know what to do, could you please help me out here?
Thank you!
Code:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
bool valid(string text);
int main (int argc, string argv[])
{
if(argc != 2)
{
printf("Usage: ./substitution key\n");
return 1;
}
if( !valid(argv[1]))
{
printf("Key must contain 26 characters.\n");
return 1;
}
string text = get_string("Plaintext: ");
printf("Ciphertext: ");
char citext[strlen(text)];
for (int i = 0; i < strlen(text); i++)
{
if(isupper(text))
{
citext[i] = toupper(argv[1][i]);
printf("%c", citext[i]);
}
else if(islower(text))
{
citext[i] = tolower(argv[1][i]);
printf("%c", citext[i]);
}
else
{
printf("%c", text[i]);
}
}
printf("\n");
}
bool valid(string text)
{
if(strlen(text) != 26)
{
return false;
}
for (int i = 0, n = strlen(text); i < n; i++)
{
if (!isalpha(text[i]))
{
return false;
}
for (int j = 0; j < n; j++)
{
if(toupper(text[i]) == toupper(text[j]) && i != j)
{
printf("Key must not be repeated.\n");
return false;
}
}
}
return true;
}