0

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.

1

It looks like it will fail here else if (isalpha(argv) == 0) (I did not read the code further).

argv is an array of strings. Review the man page for isalpha to be reminded that it takes a single character as an argument.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .