0

My solution to this problem is as follow:

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

int main(int argc, string argv[])
{
    //Verify key's solidily
    if (argc != 2)
    {
        printf("Get serious, dude.\n");
        return 1;
    }
    for(int i = 0, n = strlen(argv[1]); i < n; i++)
    {
        if ((isalpha(argv[1][i]))== false)
        {
            printf("Get serious, dude.\n");
            return 1;
        }
    }

    //Get the real key
    int key[strlen(argv[1])];
    for (int i = 0, n = strlen(argv[1]); i < n; i++)
    {
        if(isupper(argv[1]))
        key[i] = (int)(argv[1][i] - 'A');
        if(islower(argv[1]))
        key[i] = (int)(argv[1][i] - 'a');
    }

    //Process the text 
    string text = GetString();
    for (int i = 0, n = strlen(text); i < n; i ++)
    {
        char prt = text[i] + key[i];

        if(isupper(text[i]))
        {
            if(isupper(prt))
            printf("%c", prt);
            if(isupper(prt) == false)
            printf("%c", (prt - 26));
        }

        else if(islower(text[i]))
        {
            if(islower(prt))
            printf("%c", prt);
            if(islower(prt) == false)
            printf("%c", (prt - 26));
        }

        else
        printf("%c", text[i]);
    }

    printf("\n");
    return 0;
}

This program has been successfully compiled; however, when executed, a segmentation fault occurs.

I was able to pin down the problem being the second chunk of my codes:

 //Get the real key
    int key[strlen(argv[1])];
    for (int i = 0, n = strlen(argv[1]); i < n; i++)
    {
        if(isupper(argv[1]))
        key[i] = (int)(argv[1][i] - 'A');
        if(islower(argv[1]))
        key[i] = (int)(argv[1][i] - 'a');
    }

Any help would be much appreciated.

3

You did a pretty good job of narrowing the problem down!

if(isupper(argv[1]))

The isupper() function (and all it's cousins) takes a single char as input, but argv[1] is a string, not a single char. The line of code tries to shove a string down isupper()'s throat, so it chokes and throws a seg fault. You need to process one char at a time through isupper().

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

1
  • That was an utterly prompt answer! And it works! Thanks a lot! I will accept this answer as soon as the clock permits. – Makoto Dec 7 '16 at 5:21

You must log in to answer this question.

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