Friday, March 28, 2008

Parse an int range parameter

#include <stdio.h>
#include <string.h>

/**
* If str is of the form "<m>:<n>",
* set *min = m
* and *max = n. Otherwise,
* if str if of the form "<n>",
* set *min = defaultMin and
* *max = n.
* Return the number of numbers
* successfully parsed (1 or 2 indicating success,
* 0 failure).
*/
int charToIntRange(const char* str,
int defaultMin,
int* min,
int* max)
{
if (strchr(str, ':')) {
if (sscanf(str, "%d:%d", min, max) == 2) {
return 2;
}
else {
return 0;
}
}
else {
*min = defaultMin;
return sscanf(str, "%d", max);
}
}

int main(int numArgs, char** args)
{
int i;
for (i = 1; i < numArgs; ++i) {
int m;
int n;
if (charToIntRange(args[i], -1666, &m, &n)) {
printf("%d:%d\n", m, n);
}
else {
printf("failed to parse <<%s>>\n", args[i]);
}
}

return 0;
}

$ gcc -Wall charToIntRange.c
$ ./a.out 1 155:7 -3:3 :1 1: 19:-1 19:1a t15:5
-1666:1
155:7
-3:3
failed to parse <<:1>>
failed to parse <<1:>>
19:-1
19:1
failed to parse <<t15:5>>


It should probably fail with an input of "19:1a", but I'll leave off worrying about that for now.

Is the format "%[:]" portable?

No comments: