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

int main(int argc, char **argv)
{

    if ((int)argv[1] > 2147483580)
    {
        printf("Usage: ./caesar key");
    }


    else
    {
        printf("Usage: ./caesar key");
    }


    if (argc ==2 && isdigit(argv[1]))
    {
        int k = atoi(argv[1]);

        string ip = get_string("plaintext:");

    }
}

//char sum

This is the partial code which only takes input . If you run using ./ceaser it outputs correctly but upon entering acceptable value like ./ceaser 4 it outputs

~/Caesar/ $ ./ceaser 4
Segmentation fault

I tried with another approach but got the same error

    long a = 2147483580;
    if ((int)argv[1] > a)
    {
        printf("Usage: ./caesar key");
    }


    else
    {
        if (argc ==2 && isdigit(argv[1]))
        {
            int k = atoi(argv[1]);
            string ip = get_string("plaintext:");

        }
        else
        {
            printf("Usage: ./caesar key");
        }
    }

Help me out with this!!

2 Answers 2

1

This is a common newbie error. The problem lies here:

isdigit(argv[1])

The isdigit() function and all of it's issomething() functions take a single char as input. But, argv[1] is a string, not a single char. This code is taking a string and shoving it down isdigit's throat, so it chokes and coughs up a seg fault.

The code needs to check each char in argv[1], one by one. Hint: two dimensional array and a for loop.

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

0

I found out an approach to solve this-

int main(int argc, string argv[])

{

char c[strlen(argv[1])];
for (int i=0; i<strlen(argv[1]); i++ )
{
    c[i] = argv[1][i];

    //printf("%c\n", argv[1][i]);
}

printf("%s\n", c);
if (argc ==2 && isdigit(c[0]))
{
    int k = c[0];
    string ip = get_string("plaintext:");

}
else
{
    printf("Usage: ./caesar key");

}

You must log in to answer this question.

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