I am working on Caesar problem set in CS50 Harvard course and I am going step by step through the problem and am stuck on "validating the key".
Now that you know how to read the key, let’s analyze it. Modify
caesar.c
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 after printing the messageUsage: ./caesar key
. But if the argument consists solely of digit characters, you should convert that string (recall thatargv
is an array of strings, even if those strings happen to look like numbers) to an actual integer, and 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
Every time I try mine it prints out everything twice and I cannot figure out why.
int main(int argc, string argv[])
{
//If command is not 2
//Use atoi to convert a string into that number
if (argc !=2)
{
printf("Usage: ./ctest key\n");
return 1;
}
//Find length of second string
else if (argc == 2)
{
//Check if the key is a number
int k = atoi(argv[1]);
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
//Check if it is not a digit
if(!isdigit(argv[1][i]))
{
printf("Needs to be a digit\n");
return 1;
}
else
{
printf("Success\n %i \n", k);
}
}
}
}