I have a case where I'm not sure if I'll get enough input for sscanf
. Can I safely assume that sscanf
won't mess with any argument that it doesn't find?
For example, in this program:
#include <stdio.h>
int main(int argc, char** argv) {
int a = 0, b = 0, c = 0;
sscanf("1 2", "%d %d %d", &a, &b, &c);
printf("%d %d %d\n", a, b, c);
return 0;
}
The output is:
1 2 0
So, it read two of the three numbers, and didn't mess with the last one. Can I safely assume that all compilers and standard libraries will also leave the last argument alone in this case, or do I need to do something like this:
int main(int argc, char** argv) {
int a = 0, b = 0, c = 0;
if (sscanf("1 2", "%d %d %d", &a, &b, &c) != 3) {
c = 0;
}
printf("%d %d %d\n", a, b, c);
return 0;
}
You are completely safe.
In C11, 7.21.6.7 The sscanf function
7.21.6.2 The fscanf function says,
Your case is an input failure.
7.21.6.2, para 21:
That's the closest thing that I can find to an assurance that a parameter will not be modified if no corresponding input is available.
The only reference I can find in C11 is for
fscanf
, 7.21.6.2/10, which says:I interpret "is placed in" as "is assigned to", and I'd say with reasonable confidence that this means that an assignment happens if and only if there's a match, otherwise the recipient variable isn't touched.
Note that all of the variable argument are evaluated before the function call, of course; this has nothing to do with
scanf
.Guranteed. sscanf() will not assign any thing to the extra parameters. You can avoid checking for the return value for this
The C library function int
sscanf(const char *str, const char *format, ...)
reads formatted input from a string instead ofstdin
On success, the function returns the number of items in the argument list successfully filled.
On failure, This
count can match the expected number of items or be less (even zero) in the case of a matching failure.
In the case of an input failure before any data could be successfully interpreted, EOF is returned.If there are too many arguments for the conversion specifications, the extra arguments are evaluated but otherwise ignored.
The results are not defined if there are not enough arguments for the conversion specifications.
All three functions
(fscanf, scanf, and sscanf) return
the number of input items that were successfully matched and assigned. The return value does not include conversions that were performed but not assigned (for example, suppressed assignments).If you check with the Number of Items count That might become false in some cases.
From http://pubs.opengroup.org/onlinepubs/009695399/functions/scanf.html:
Edit: As Kerrek correctly noticed, the above statement does not apply here. It is about
sscanf("1", "%d", &a, &b, &c)
, and not aboutsscanf("1", "%d %d %d", &a, &b, &c)
as in the question.