In: Computer Science
In C programming using C11 library, how can we validate command line arguments?
meaning for example if we input "./math 65 45 2.3 1 0 68" into the terminal, how can we validate that the numbers "65 45 2.3 1 0 68" are floats and not chars? In other terms the program should display and error message if the command line arguments are not floats and if they are floats, the program carries on as usual.
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int allOk = 1; // flag to check whether argument is float
int index = 0; // index of the not-a-float input
// display all the command line arguments
// loop index starts from 1 as, 0th element is the program
name
printf("Arguments: ");
for(int i = 1; i < argc; i++)
{
printf("%s ", argv[i]);
}
printf("\n");
// check each argument
for(int i = 1; i < argc; i++)
{
// this loop iterates over the length of the ith argument
for(int j = 0; j < strlen(argv[i]); j++)
{
// get the ascii value of each character of the ith argument
int ascii = (int)argv[i][j];
// if ascii is within the range: 48 to 57 (digits: 0 to 9)
if(ascii >= 48 && ascii <= 57)
allOk = 1; // set flag
else
{
// if single argument is not float, set flag to 0 and break the
inner loop
allOk = 0;
break;
}
}
// if non-float input is encountered, get the index and breeak the
outer loop
if(allOk == 0)
{
index = i;
break;
}
}
// finally, check the flag for intended input
if(allOk == 1)
printf("All are floats!\n");
else
printf("Invalid input: %s\n", argv[index]);
return 0;
}'
****************************************************************** SCREENSHOT *********************************************************