Home > Enterprise >  Problem with the Caesar problem set on cs50 online course
Problem with the Caesar problem set on cs50 online course

Time:04-14

I'm on the stage where we need to correctly setup the command line argument to take only digits and to break out of the code if the user types anything else other than a digit. (leaving it empty, inputting two digits, inputting text, inputting two pieces of text etc.)

So I made the program work correctly if the user types more than one command line argument or one command line argument which isn't a digit. My problem is that if I leave the command line argument blank the program gives me a segmentation fault and it doesn't work as intended if I type a single command line like "1d". Can anyone tell me where I went wrong? I'm stuck. Here's the code:

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>    
    
bool only_digits(string argv[]);
int main(int argc, string argv[])
{
    bool digits = only_digits(argv);
    if(argc != 2 || digits == false)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
    else
    {
        return 0;
    }
}
bool only_digits(string argv[])
{
    bool digit = false;
    for(int i = 0; i < strlen(argv[1]); i  )
    {
        if(isdigit(argv[1][i]))
        {
            digit = true;
        }
    }
    return digit;
}

Here are all my inputs

CodePudding user response:

You have two problems:

  1. You're calling only_digits() before checking whether argv[1] exists. So you get a segfault if there are no command-line arguments. Fix this by calling only_digits() after the argc check.
  2. The condition in only_digits() is backwards. It returns true if any character is a digit, but it's supposed to return true only if all the characters are digits.
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
    
bool only_digits(string argv[]);

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

bool only_digits(string argv[])
{
    for(int i = 0; i < strlen(argv[1]); i  )
    {
        if(!isdigit(argv[1][i]))
        {
            return false;
        }
    }
    return true;
}
  • Related