0

Here is my program caesar, pset 2. I don't know where it is going wrong. whenever I run it with input, Segmentation fault (core dumped) error appears on terminal. how to fix this?

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

bool only_digits(string s);
int k, flag =0;

int main (int argc, string argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
    }
    else if (only_digits(argv[1]))
    {
    k = atoi(argv[1]);
    flag = 1;
    }
    else
    {
    printf("Usage: ./caesar key\n");
    return 1;
    }

if (flag == 1)
{
// Ask user for plaintext
string ptext = get_string("plaintext = ");
string ctext[strlen(ptext)];

// Convert ptext to ctext.
for (int i=0; i<=strlen(ptext); i++)
{
    if (isupper(ptext[i]))
    {
        ctext[i] = (ptext[i] + k - 65) % 26 + 65;
    }
    else if (islower(ptext[i]))
    {
     ctext[i] = ((ptext[i] + k - 97) % 26 + 97);
    }
    else
    {
        ctext[i] = ptext[i];
    }
}
// Print ctext.
printf("ciphertext = %s\n", ctext);
}
}


bool only_digits(string s)
{
    if (isdigit(s))
   {
     return true;
    }
    else
    {
        return false;
    }
}

1 Answer 1

3

Look at this line of code:

if (isdigit(s))

The isdigit() function takes a single character as input, but s is a string. This triggers a seg fault.

The code needs to process each char in the string, one by one, not the entire string at once. Hint: a for loop is your friend.

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 .