0

I am trying to complete the Caesar excercise on pset 2. My code compiles fine however it seems to give me me the output Usage: ./caesar key even though I input an int. Any help is much appreciated on where I am going wrong.

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

int main(int argc, string argv[])

{

    if (argc == 2 && (atoi(argv[1]) > 0))
     for(int i = 0, len = strlen(argv[1]); i < len; i++)
        {
           char n = argv[1][i];
           int digit = isdigit(n);


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

          else
            {
                printf("Success\n %i", digit);
                return 0;
            }  


        }

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


}

1

Let's look at what's really happening:

char n = argv[1][i];
       int digit = isdigit(n);

       if (n != digit)

You have to thoroughly understand every step here. First, the code will copy the specified char from argv[1] to n.

Second, the code will check whether the char stored in n is a digit. It will then store the return value from isdigit() in digit. But what is that value???? Do you really know? The value returned will be 0 if n is NOT a digit, or will be a specific power of 2 if it is. (All of the is{something}() functions will return a certain power of 2 if true and 0 if false. You can write a simple program to figure out what it is, or just print out the value of digit.)

Also, remember that an if( ) statement interprets the test result as follows: if the overall result is zero, it's false. ANYTHING ELSE is interpreted as true, including negatives.

Finally, the code compares the value of n to the value of digit. The odds are almost zero that they will match, so it's going to return 1 virtually every time.

This is a case of overcomplicating the code. Think about what you're trying to determine. Is the char in question not a digit????

   if (! isdigit(argv[1][i]) )

Just cut to the chase and check! This is much simpler and much more efficient.

This is a good lesson. Whenever you write working code, it's always good to go back, look at it and see if it can be simplified!

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 .