0

In this problem set, we are supposed to obtain one argument (which comprises of digits), failing which, the user is prompted with a message, Usage: ./caesar key. I have attached the problem statement below.

Here is the problem statement from the problem set for context.

Modify caesar.c at right such that instead of printing out the command-line argument provided, your program instead checks to make sure that each character of that command line argument is a decimal digit (i.e., 0, 1, 2, etc.) and, if any of them are not, terminates (with a return code of 1) after printing the message Usage: ./caesar key.

But if the argument consists solely of digit characters, you should convert that string (recall that argv is an array of strings, even if those strings happen to look like numbers) to an actual integer. As luck would have it, a function, atoi, exists for exactly that purpose. Here’s how you might use it:

int k = atoi(argv[1]);

Once saved, print out the integer, as via %i with printf. So, for example, the behavior might look like this:

$ ./caesar 20 
Success 20 

or

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

Problem

When I input an integer(say 20, for convenience), I am prompted with the following outputs in the command line twice- not once as is desired:

./caesar
Success
20

Success
20

instead of

./caesar
Success
20
int main(int argc, string argv[])
{      
  if (argc != 2)
  {
    printf("Usage: ./caesar key\n");
    return 1;
  }

  string s = argv[1];  

  for (int i=0, n = strlen(s); i < n ; i++)          
  {
    if(!isdigit(s[i]))
    {
        printf("Usage: ./caesar key \n");
        return 1; 
    }    
    else 
    {    
        printf("Success\n%s\n", argv[1]);        
    }
  }        
}

1 Answer 1

1

Don't print anything in the if(!isdigit(s[i]))'s else path. Abort execution on non-digit character, but no action for digit character (or at least, not yet).

Continue with the code after that for loop.

2
  • What might that code look like? sorry, if it's not too much of a trouble, could you please provide the requisite lines of code?
    – Lim Dion
    Commented Aug 5, 2019 at 10:22
  • Remove the else path in the loop. And after the for loop, continue with the int k = atoi(argv[1]); from the problem description (and printf as you want, either one per line above and below the conversion, or both after the atoi)
    – Blauelf
    Commented Aug 5, 2019 at 13:35

You must log in to answer this question.

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