Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: sscanf assignment suppression and the return value

Tags:

c

scanf

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') {
like image 800
morgoe Avatar asked Oct 28 '25 07:10

morgoe


2 Answers

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).

like image 181
Jonathan Leffler Avatar answered Oct 29 '25 20:10

Jonathan Leffler


A simpler test, using just the scanf return value instead of one test of the return value and one of the character count, is possible with:

if (1 == sscanf(mystring, "%d %c", &num, &(char){0}))

This works because, if there is any character after the trailing spaces are consumed, a second assignment is performed, so the return value is 2 instead of 1.

(The (char){0} is a compound literal that provides a temporary object to hold the assigned char, after which it is discarded.)

like image 28
Eric Postpischil Avatar answered Oct 29 '25 19:10

Eric Postpischil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!