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
  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.

0

Your explanation was very useful! thanks!

I cannot figure out why am I getting these results?

I'm currently only trying to validate the Numeric Key when typing 20x as a command-line argument get Usage: ./caesar Key

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

int main (int argc, string argv[])
{
    int Key = (int)argv[1];

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

    }
    else 
    {
        printf("Usage: ./caesar Key\n");
    }
}

Prompt

You must log in to answer this question.

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