You can use a function like strtol() , which converts an array of characters to long.
It has a parameter that allows you to detect the first character that was not converted properly. If this is something other than the end of the line, you have a problem.
Refer to the following program for an example:
#include <stdio.h> #include <stdlib.h> int main( int argc, char *argv[]) { int i; long val; char *next; // Process each argument given. for (i = 1; i < argc; i++) { // Get value with failure detection. val = strtol (argv[i], &next, 10); // Check for empty string and characters left after conversion. if ((next == argv[i]) || (*next != '\0')) { printf ("'%s' is not valid\n", argv[i]); } else { printf ("'%s' gives %ld\n", argv[i], val); } } return 0; }
By running this, you can see it in action:
pax> testprog hello "" 42 12.2 77x 'hello' is not valid '' is not valid '42' gives 42 '12.2' is not valid '77x' is not valid
source share