Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1 view
in Technique[技术] by (71.8m points)

c - sscanf behaviour / return value

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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). If there was an integer with additional characters, it would return 2 as it was able to assign both parameters.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...