I’m trying to use sscanf in C to get some values from a string. However, if the string has more values than I want, I need it to throw an error. ie. if I want an integer, “2” should be ok, but “2 5” should crash.
Now using the return value on sscanf like so:
if (sscanf(mystring, "%d %*s", &num) == 1)
doesn’t work because it’ll return 1 even if the string is longer. I CAN do this:
char tmpString [100];
if (sscanf(mystring, "%d %s", &num, tmpString) == 1)
which works fine, but it’s not particularly nice. Is there another way? Can I use the assignment suppression and still get the return value I want?
edit
This is the code I’ve used:
char c; // This is a global variable, just gets used over and over.
sscanf(mystring, "%d%c", &num, &c);
if (c == '\n') {
One possibility is:
The
%nis part of C89. It is not a particularly commonly used (or widely known) conversion specification. It does not get counted as a conversion (hence the test for1).