I am so stuck. Been trying for days. I need to validate that each char input into argv[1]
is a number but I have tried isdigit
, isalpha
, char
, atoi
conversion without any success. I'm still new at coding. I got frustrated and deleted everything to start over again but here's where I'm at now.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
if (argc == 2)
{
for (int k = 0; k <strlen(argv[1]); k++)
{
printf("Success!\n");
printf("%s\n", argv[1]);
}
}
else
{
printf("Usage: ./caesar key\n");
}
}
Here is where I was at before. I kept getting a sanitization error everytime I tried to run this:
#include <cs50.h>
#include <stdio.h>
#include <string.h>
include <ctype.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
if (isdigit(argv[1]))
{
if(atoi(argv[1]))
{
if (argc == 2)
{
for (int x = 0; x < strlen(argv[1]); x++)
{
printf("Success!\n");
printf("%s", argv[1]);
}
}
}
}
else
{
printf("Usage: /caesar key\n");
}
}
Any help would be appreciated!
A quick and dirty example on onlinegdb:
Didn't test a lot...
#include <stdio.h>
#include <string.h>
int main(int argc, char * argv[])
{
if (argc == 2)
{
int n = strlen(argv[1]);
for (int k = 0; k < n; k++)
{
if ( isdigit(argv[1][k]) )
{
printf("%c is a digit\n", argv[1][k]);
}
else
{
printf("%c is not a digit\n", argv[1][k]);
}
}
}
else
{
printf("Error\n");
}
}
Remember that argv[1]
is a string, ie. an array of characters (with a null chracter at the end).
So you have to travel all the characters of this array.
EDIT: good comment from chmike in the other answer.