0

My code compiles, but when I run it I get segmentation fault. What is wrong?

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

void ciphertext(string k, string p);

int main(int argc, string argv[])
{
    string k;
    string p; 

    if (argc == 2)
    {
        k = argv[1];
        while (isalpha(argv[1])) // Making sure it is an alphabetical keyword.
        {
            printf("plaintext: ");
            p = get_string();
        }
    }
    else
    {
        printf("Error: <keyword>\n");
        return 1;
    }

    printf("ciphertext: ");
    ciphertext(k, p);

}

void ciphertext(string k, string p)
{
    int j;
    int key;
    for (int i = 0, n = strlen(p); i < n; i++)
    {
        for (j = 0, n = strlen(k); j == n; j++)
        {

            if (isupper(k[j]))
            {
                k[j] = k[j] - 65;
            }
            else if (islower(k[j]))
            {
                k[j] = k[j] - 97;
            }
        }

        // Converting the key to an integer.
        key = atoi(&k[j]);

        char cha;
        if (isalpha(p[i]))
        {
            if (isupper(p[i]))
            {
                cha = p[i] - 65;
                printf("%c", ((cha + key) % 26) + 65);
            }
            else if (islower(p[i]))
            {
                cha = p[i] - 97;
                printf("%c", ((cha + key) % 26) + 97);
            }
        }
        else 
        {
            printf("%c", p[i]);
        }
    }
    printf("\n");
}

1 Answer 1

0

The function isalpha only works on single char types, not strings, i.e. it will only check one letter. To check a whole string, you have to loop over the length of the string and check each letter individually. Hopefully this will solve your first problem ;)

1
  • This solved the segmentation fault, but the cipher isn't working.
    – user14816
    Commented Feb 19, 2017 at 15:39

You must log in to answer this question.