0

I hope my question was worded right but I'm trying to solved pset2 caesar and i don't understand how to print something only if all the possible values of a variable fit the condition. If I input "./caesar 20x" in my code right now, it prints "Success" after only checking the first number. How do I fix this?

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

int main(int argc, string key[])
{
if (argc == 1 || argc > 2)
{
    printf("Usage: ./caesar key\n");
    return 1;
}

if (argc == 2)
{
    for (int i = 0, n = strlen(key[1]); i < n; i++)
    {
        int ASCII = key[1][i];
            
        if ((ASCII > 57) || (ASCII < 48))
        {
            printf("Usage: ./caesar key\n");
            return 1;
        }
        
        if ((ASCII >= 48) && (ASCII <= 57))
        {
            printf("Success\n");
            return 0;
        }
    }
}
}

1 Answer 1

1

It does this because of the logic that was implemented in the code. Think about what the code does. Even though it's running a loop, the code is going to check the first character in the input string. Whether it's a number or not, it's going to terminate because of the return statements in both if statements. A return statement in main will immediately terminate the program when encountered.

You need to rethink the logic. The code needs to check every character. If something is not a number, then the usage messsage needs to be printed and the program terminated immediately. There's no reason to continue testing.

More importantly, if the current char being tested is a number, then testing simply needs to move on to the next character. The success message should only be processed (or more code executed) when all characters have been tested, ie, the loop has finished.

Here are a couple programming tips. There are several library functions that test characters: isalpha(), isdigit(), isupper(), islower() and others in that family. They are your friends. ;-)

Seccond, look at the two if statements in the code above. If the first if test fails, the second simply must be true. In those circumstances, it's only necessary to have an else, not an else if. Else if is used when there are 3 or more possible outcomes. When there are only two, an else is usually sufficient, or maybe even unnecessary.

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

You must log in to answer this question.

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