0

I'm working through PSet 2: Caesar, and I'm stuck on the step called "Checking the key". The instructions read as follow:

Checking the Key

Now that your program is (hopefully!) accepting input as prescribed, it’s time for another step. Add to caesar.c, below main, a function called, e.g., only_digits that takes a string as an argument and returns true if that string contains only digits, 0 through 9, else it returns false. Be sure to add the function’s prototype above main as well.

This is the code I've tried with.

[code removed per academic honesty guidelines]

When I compile the code, I don't run into any errors. When I run the code, nothing is output regardless of whether I try ./caesar 10 or ./caesar hello.

Any advice?

1 Answer 1

1

@Devirider's answer will work, but it doesn't explain the issue. So let's look at what's happening with this function:

for(int i = 0, len = strlen(key); i < len; i++)
    {
        if(isdigit(key[i]))
        {
            printf("TRUE");
            return 0;
        }
    }
    return 1;

There are two logic issues in play here.

First, the if statement will check if the chars are digits, one by one. As soon as it finds the first digit, it executes the return statement and stops checking any further chars. That means that if there are any non-digits later, it didn't check them. The if statement should be checking for non-digits instead. If it finds one, then return false.

This brings us to the next issue - the return values. There are two different practices for return values that are contradictory to each other. One is the value returned from a terminating program. Specifically, it will return 0 when a program completes successfully and will return a non-zero value to indicate an aborted execution or an error. The non-zero can also indicate what the error or condition was when it terminated.

Then, there's the use of 0 and 1 (or any non-zero value). If you're using a number as a bool, you have to understand how the compiler interprets the values. Zero, or 0, is always interpreted as FALSE!!! Any other non-zero, positive or negative, including 1, is interpreted as TRUE. So, that means that the code above was returning false when intending to return true and vice versa.

Fix these problems and you're all set. ;-)

You must log in to answer this question.

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