C: sscanf assignment suppression and the return value

c, scanf

Solution

One possibility is:

int pos;
if (sscanf(mystring, "%d %n", &num, &pos) == 1)
{
    if (mystring[pos] != '\0')
        ...oops...extra data...
    else
        ...only number...
}
else
    ...not even one number...

The `%n` is 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 for `1`).

Problem

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') { ```

Original source