0

My code accepts numbers with letters, e.g. 2x. When running check 50 I get this error 'handles non-numeric key, timed out while waiting for program to exit. Log running ./caesar 2x..'

The code is not accepting single letters, special characters, negative numbers or empty entries. I thought that by adding

!isdigit(*argv[1]) || isalpha(*argv[1])

I'm already rejecting any letters. I just don't know how I can be more explicit about it and would be grateful for any help.

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

int main(int argc, string argv[])
{
    if (argc != 2 || !isdigit(*argv[1]) || isalpha(*argv[1]))
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }
    else
    {
        int k = atoi(argv[1]);
        string p = get_string("Plaintext: ");
        int n = strlen(p);
        printf("%i\n", k);
        printf("ciphertext: ");
        for (int i = 0; i < n; i++)
        {
            if (isalpha(p[i]))
            {
                if (isupper(p[i]))
                {
                    printf("%c", 'A' + (p[i] - 'A' + k) % 26);
                }
                else if (islower(p[i]))
                {
                    printf("%c", 'a' + (p[i] - 'a' + k) % 26);
                }
            }
            else
            {
                printf("%c", p[i]);
            }
        }
        printf("\n");
    }

}
1

Most of the students find logical operators confusing, especially when there are several together in the same sentence. I suggest that you think carefully about which cases is true, and in which cases it is false, the IF condition of the start of your program.

I would prefer to separate in several different IF conditions, the most logical thing is to verify if the number of arguments is two, and if not, exit the program.

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

Once we know that there are two arguments, we check that it is a decimal digit, for this the isdigit function is sufficient, the problem is argv [1], it is a string, although we write a terminal 2 as an argument, this will be treated as a string, take a look at the atoi() function (header: stdlib.h), this function converts a string to a decimal digit, if the function cannot convert the string it returns zero, watch out for integer overflows because it produces undefined behavior, with this you should be able to start.

You must log in to answer this question.

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