2

my program compiles but when I input the plain text and run it, I get a segmentation fault. What am I doing wrong?

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main (int argc, string argv[])
{
   int key = atoi(argv[1]);
   if (argc != 2)
    {
        printf("Type ./caesar key \n");

        return 1;
    }

        printf("Type your text please: \n");
        string text = GetString();
        char cipher;
    if(isalpha(text))
    {
        for(int i = 0, n = strlen(text); i < n; i++)
        {
             if(isupper(text[i]))
             {
                cipher = (text[i] - 'A') + key;
                cipher = cipher % 26;
                printf("%c\n", cipher);
             }

             if(islower(text[i]))
             {
                 cipher = (text[i] - 'a') + key;
                 cipher = cipher % 26;
                 printf("%c\n", cipher);
             }
        }


    }

}
3

You actually have two problems with seg faults. First, the one that you probably haven't seen yet. The code tries to assign argv[1] to key before verifying it exists on the next line. If you run the program without a key, it will seg fault because of this.

Next is this:

if(isalpha(text))

The isalpha() function takes a single character as input. The code is trying to force a string down it's throat, so it chokes and causes a seg fault. You need to process each letter, one at a time.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

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