I'm currently working on Caesar and I'm trying to go through each step in turn to complete it. As the problem set requires, I've written code that runs from the command line.
The code below correctly returns 'Usage: ./caesar key' if a user tries for enter more than one argument vector.
The code also uses isDigit to identify whether the first char of the argv string is a digit or not. However, I cannot work out how to iterate down the string to check all the chars to see if they are digits or not.
This section of the task requires that - assuming the user enters a single argv - the program returns a message that reads: Success argv
but only if the argv is a number.
Currently, if a user enters, say: ./caesar 20x
The program would (incorrectly) return: Success 20x
However, if a user enters, say: ./caesar x20
The program would (correctly) return: Usage: ./caesar key
This makes me think that my program is checking how many argument vectors there are and the first char in the string but not each char in the string.
I have tried to work out how to iterate or loop down the string but everything seems to make the problem worse! Any advice you can give gratefully received.
The code is below:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int main(int argc, char *argv[])
{
if (argc ==2 && isdigit(*argv[1]))
{
printf ("Success\n");
printf ("%s\n", argv[1]);
}
else
{
printf ("Usage: ./caesar key\n");
}
}
Update - I've tried again, but this (though different) is having the same results!
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
int main(int argc, string argv[])
{
if (argc != 2)
{
printf ("Usage: ./caesar key\n");
}
else if (argc == 2)
{
int i = atoi(argv[1]);
bool isKeyValid = true;
int len = strlen(argv [1]);
for (i = 0; i < len; i++)
{
if (isdigit(argv[1][i++]) == false)
{
isKeyValid = false;
i = len;
printf ("Usage: ./caesar key\n");
}
else if (isdigit(argv[1][i++]) == true)
{
isKeyValid = true;
i = len;
printf ("Success\n");
printf ("%s\n", argv[1]);
}
}
}
}