Sscanf and trailing characters

I am trying to use sscanffor a simple test and conversion, but I am having a problem with it ignoring the final garbage in the string. My sample code is:

char *arg = "some user input argument";
int val = 0;
if (sscanf(arg, "simple:%d", &val) == 1) {
    opt = SIMPLE;
} else if (strcmp(arg, "none") == 0) {
    opt = NONE;
} else {
    // ERROR!!!
}

This works great for expected inputs, for example:

arg = "simple:2"  --> opt = SIMPLE  val = 2
arg = "none"      --> opt = NONE    val = 0

But my problem is that trailing characters after a “simple” value are silently ignored

ACTUAL : arg = "simple:2GARBAGE" --> opt = SIMPLE  val = 2
DESIRED: arg = "simple:2GARBAGE" --> ERROR!!!

What is an easy way to get sscanf to report on the trash? Or, since I read "scanf is evil", is there a simple (possibly 1-linear) alternative sscanfto solve the above problem?

+3
source share
2 answers

sscanf()for extra char. Could not find it.

char ch;
// If _nothing_ should follow the `int`
if (sscanf(arg, "simple:%d%c", &val, &ch) == 1) Success();
// or if trailing white-space is OK
if (sscanf(arg, "simple:%d %c", &val, &ch) == 1) Success();

Another idiomatic solution uses %n

int n;
// If _nothing_ should follow the `int`
if (sscanf(arg, "simple:%d%n", &val, &n) == 1 && arg[n] == '\0') Success();
// or if trailing white-space is OK
if (sscanf(arg, "simple:%d %n", &val, &n) == 1 && arg[n] == '\0') Success();
+5

:

char rest[64] = "";
[...]
if ( sscanf(arg, "simple:%d%s", &val, rest) == 1 ) {

rest.

, %s, %d, , . rest .

. .

+4

All Articles