I'm stuck on this for days. I've also tried other answers on this question but still not able to understand what's causing Segmentation Fault when I enter a string as key after ./vigenere. Here's my code:
int main(int argc, string argv[])
{ if (argc != 2) {
printf("Incorrect command-line argument\n");
return 1;
}
else if (isalpha(argv) == 0)
{
printf("Enter alphabets only\n");
return 1;
}
string key = argv[1];
string text = get_string("Plaintext: ");
printf("ciphertext: ");
int cipher;
for (int i = 0, j =0; i < strlen(text); i++, j++)
{
if (j >= strlen(key))
{
j = 0;
}
if (text[i] == ' ')
{
j--;
}
if (isalpha(text[i]))
{
if (isupper(text[i]))
{
char ai_key = (toupper(key[j]) - 'A');
char ai_text = (text[i] - 'A');
cipher = (ai_key + ai_text) % 26;
printf("%c", cipher + 'A');
}
else if (islower(text[i]))
{
char ai_key = (tolower(key[j]) - 'a');
char ai_text = (text[i] - 'a');
cipher = (ai_key + ai_text) % 26;
printf("%c", cipher + 'a');
}
}
else
{
printf("%c", text[i]);
}
}
printf("\n");
return 0;
}
Same code, with hard-coded strings for text & key works fine in Code::Blocks IDE.