Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sscanf behaviour / return value

Tags:

c

scanf

I'm a novice learning C and trying to understand the following code from an online lecture. It scans a string for an integer; if characters are encountered, the sscanf fails.

int n; char c;
if (sscanf(string, " %d %c", &n, &c) == 1)
    //return the integer

else
    // fail

I've read the the man pages for sscanf and am still confused about checking the return value and why this code works. They state that "These functions return the number of input items assigned".

If sscanf encounters characters only, it writes them to &c...but in that case &n won't have been written to. In this case, I would have thought that the return value of sscanf would still be 1?

like image 778
cortexlock Avatar asked May 27 '13 19:05

cortexlock


People also ask

What is the return value of sscanf?

In case sscanf has successfully read %d and nothing else, it would return 1 (one parameter has been assigned). If there were characters before a number, it would return 0 (no paramters were assigned since it was required to find an integer first which was not present).

How to use sscanf () function?

The sscanf () function reads data from buffer into the locations given by argument-list. If the strings pointed to by buffer and format-string overlap, behavior is undefined. Each entry in the argument list must be a pointer to a variable of a type that matches the corresponding conversion specification in format-string.

What is the return value of EOF?

Return Value On success, the function returns the number of items in the argument list successfully filled. 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, EOFis returned.

What is the format argument in scanf?

The sscanf function reads data from buffer into the location given by each argument. Every argument must be a pointer to a variable with a type that corresponds to a type specifier in format. The format argument controls the interpretation of the input fields and has the same form and function as the format argument for the scanf function.


1 Answers

Your sscanf(string, " %d %c") will return EOF, 0,1 or 2:

2: If your input matches the following
[Optional spaces][decimal digits1][Optional spaces][any character][following data not read]

1: If your input failed above but matched the following
[Optional spaces][decimal digits1][Optional spaces][no more data available]

0: If your input, after white-space and an optional sign, did not find a digit: examples: "z" or "-".

EOF: If input was empty "" or only white-space2.


1 The decimal digits may be preceded by a single sign character: + or -.

2 Or rare input error.

like image 180
chux - Reinstate Monica Avatar answered Oct 12 '22 22:10

chux - Reinstate Monica