0

I am working on Caesar problem set in CS50 Harvard course and I am going step by step through the problem and am stuck on "validating the key".

Now that you know how to read the key, let’s analyze it. Modify caesar.c such that instead of printing out the command-line argument provided, your program instead checks to make sure that each character of that command line argument is a decimal digit (i.e., 0, 1, 2, etc.) and, if any of them are not, terminates after printing the message Usage: ./caesar key. But if the argument consists solely of digit characters, you should convert that string (recall that argv is an array of strings, even if those strings happen to look like numbers) to an actual integer, and print out the integer, as via %i with printf. So, for example, the behavior might look like this:

$ ./caesar 20
Success
20

or

$ ./caesar 20x
Usage: ./caesar key

Every time I try mine it prints out everything twice and I cannot figure out why.

int main(int argc, string argv[])

    {
//If command is not 2
//Use atoi to convert a string into that number
if (argc !=2)
{
    printf("Usage: ./ctest key\n");
    return 1;
}

//Find length of second string

else if (argc == 2)
{
    //Check if the key is a number
    int k = atoi(argv[1]);
    for (int i = 0, n = strlen(argv[1]); i < n; i++)
    {
    //Check if it is not a digit
        if(!isdigit(argv[1][i]))
        {
            printf("Needs to be a digit\n");
            return 1;
        }
    
        else
        
        {
            printf("Success\n %i \n", k);
        }
     }
  }
}
Siddhant
  • 626
  • 1
  • 7
  • 20

1 Answers1

3

In order to meet the requirements for the program's output, you have to move not only the success printout outside of the for loop, but also remove the Needs to be a digit printout. You don't even need a loop, e. g.:

int main(int argc, char *argv[])
{
    if (argc != 2 || argv[1][strspn(argv[1], "1234567890")])
    {
        puts("Usage: ./caesar key");
        return 1;
    }

    int k = atoi(argv[1]);
    printf("Success\n%i\n", k);
}
Armali
  • 18,255
  • 14
  • 57
  • 171