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
withprintf
. 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]);
}
}
}