0

So, in Caesar when validating the key they asked to check if all the characters in the command line argument provided are digits and only printout "Success" and the digits as an integer if all the chars in the argument are digits. But when I run my program instead of printing out this: Required output it prints out this: My output

It prints out everything twice.

Here is my code. Please help as best you can as I´ve spent a lot of time on this and can't solve the issue.

Thanks :)

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

int main(int argc, string argv[])
{
if (argc == 2 )
{
    string arg = argv[1];
    for (int i = 0, n = strlen(arg); i < n; i++)
    {

        if (isdigit(arg[i]))
        {
            int key = atoi(arg);
            printf ("Sucess\n%i\n", key);
        }
        else
        {
            printf ("Usage: ./caesar key\n");
        }
    }

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

Program doesn't know if all the characters in key are digits until after it has processed all of them. The "Success" message should come after the for loop is finished. And remember this hint from the spec:

Recall that we can return nonzero values from main to indicate that our program did not finish successfully.

As soon as a non-digit is found, the program should exit (ie return from main).

Before any changes to the program, use the argument 2x0. It may give you more insight into the process flow.

1
  • Thanks! I finally figured it out.
    – ehsansth
    Mar 14 at 19:45

You must log in to answer this question.

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