0

Excuse me,

When I practice the pset2 program, I follow the step at 'Validating the Key'.

But I have the problem like below code, I want to compiler and output look like as

$ ./caesar 20 Success 20

or

$ ./caesar 20x Usage: ./caesar key

but this was unexpected.

help me~pls.

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

int main(int argc, string argv[])
{
int k;
int num;
for(int i=1; i<argc; i++)
{
        for(int j=0,n=strlen(argv[i]); j<n; j++)
        {
            k = atoi(&argv[i][j]);
            //printf("K:%i\n",k);
            //printf("&argv[%i][%i]:%s \n",i,j,&argv[i][j]);
            if(atoi(&argv[i][j])!=0)
            {
              printf("Success\n");
            }
            else
              printf("Usage: ./caesar key\n");
           // printf("argv[%i][%i]:%c\n",i,j,argv[i][j]);
        }

}
return 0;
}

enter image description here

1 Answer 1

1
  1. You are meant to reject any number of command-line arguments other than one (means argc should be 2).

  2. To test whether a given character is numeric/alphabetic, you can use the isdigit/isalpha function (actually implemented as a macro, so mistakes in code might show up in weird ways), like if (isalpha(argv[1][j])). Or, test a range, like if (argv[1][j] >= '0' && argv[1][j] <= '9') or if (argv[1][j] >= 'A' && argv[1][j] <= 'Z' || argv[1][j] >= 'a' && argv[1][j] <= 'z') (&& has precedence over || like * has over +). If you want to negate that last expression without some ! in front of everything, have fun with De Morgan's laws (it looks worse than it is). And keep in mind that non-alphabetic does not mean numeric or the other way around. Punctuation is neither nor. So test for good or non-good, not specific bad characters.

  3. On hitting a "bad" character and printing a usage notice, return with the required exit code, returning will automatically abort any loops you're in, any code left. On hitting a "good" character, there's no immediate action associated. After your loop, you would know the whole word is right.

You must log in to answer this question.

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