0

im trying to make it so my program returns Success after it checks whether the provided argument is all digits. i can see why this code prints success 3 times if i provide a 3 digit number as the argument, as i mistakingly coded it in a way that prints success after each successful iteration through argv[1]. i am confused as to how i can make it such that Success is only printed once, after the program is done iterating through the argument and has confirmed that it is indeed all digits. here is my code:

int main(int argc, string argv[])
{
    if (argc == 2)
    {
        for (int i = 0; i < strlen(argv[1]); i++)
        {
            if (isdigit(argv[1][i]) == false)
            {
             printf("Usage: ./caesar key\n");
             return 1;
            } else {
                printf("Success\n");
            }
         }
    }

    if (argc == 1 || argc >= 3)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
}

here is the output for a given argument:

$ ./caesar 50
Success
50
Success
50

thanks for the help. i will also gladly accept tips on how i can better code this solution.

1 Answer 1

1

Maybe you're just overthinking it a little? ;-)

Just move the printf(Success) statement below the for loop. If the test fails, it's going to exit through the return statement. Otherwise, the code has to drop out of the loop, at which point it must have passedm so that's when you print a success message.

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

3
  • to clarify, return 0 will stop the entire program? not just the loop?
    – owwix
    Dec 5, 2019 at 0:49
  • Close, but there's more. If a return statement is executed in main, it immediately terminates the program. If there's a return value following, that value will be returned to the OS. No matter the return value (or if there's none), the program will still terminate. However, if the return statement is in a function and not main, it will terminate only the function and return to the calling code in the same manner. The calling code (main or another function) will continue to execute from that point. Any questions? ;-)
    – Cliff B
    Dec 5, 2019 at 0:55
  • haha i just made a comment regarding that but turns out you beat me to it, thanks for the prompt response as always :)
    – owwix
    Dec 5, 2019 at 0:57

You must log in to answer this question.

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