You can analyse a string (const char *
) in order to retrieve the integer value it describes as text thanks to the sscanf()
standard function.
With a similar idea as printf()
, a format string describes what we expect: here we want an integer so "%d"
is used.
This function returns the number of conversion that were successfully performed.
Here we want only one conversion ("%d"
) so the expected result is 1.
If this result is not 1, it means that the input string did not describe an integer so no value was extracted and it makes no sense using the integer (which is still uninitialised).
/**
gcc -std=c99 -o prog_c prog_c.c \
-pedantic -Wall -Wextra -Wconversion \
-Wc++-compat -Wwrite-strings -Wold-style-definition -Wvla \
-g -O0 -UNDEBUG -fsanitize=address,undefined
$ ./prog_c 2 abc 10 def
argv[0] is <./prog_c>
argv[1] is <2>
square of value is 4
argv[2] is <abc>
argv[3] is <10>
square of value is 100
argv[4] is <def>
**/
#include <stdio.h>
int
main(int argc,
char **argv)
{
for(int i=0; i<argc; ++i)
{
printf("argv[%d] is <%s>\n", i, argv[i]);
int value;
if(sscanf(argv[i], "%d", &value)==1)
{
printf(" square of value is %d\n", value*value);
}
}
return 0;
}