C语言 sscanf 行为/返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16779633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sscanf behaviour / return value
提问by drjimmie1976
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.
我是学习 C 的新手,并试图从在线讲座中理解以下代码。它扫描一个字符串中的一个整数;如果遇到字符,sscanf 将失败。
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".
我已经阅读了 sscanf 的手册页,但仍然对检查返回值以及此代码有效的原因感到困惑。他们声明“这些函数返回分配的输入项数”。
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?
如果 sscanf 只遇到字符,它会将它们写入 &c...但在这种情况下 &n 不会被写入。在这种情况下,我会认为 sscanf 的返回值仍然是 1?
采纳答案by Aneri
In case sscanf has successfully read %dand 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 2as it was able to assign both parameters.
如果 sscanf 已成功读取%d并且没有其他内容,它将返回1(已分配一个参数)。如果数字之前有字符,它将返回0(没有分配参数,因为它需要首先找到一个不存在的整数)。如果有一个带有附加字符的整数,它将返回,2因为它能够分配两个参数。
回答by chux - Reinstate Monica
Your sscanf(string, " %d %c")will return EOF, 0,1or 2:
您sscanf(string, " %d %c")将返回EOF, 0,1或2:
2: If your input matches the following
[Optional spaces][decimal digits*][Optional spaces][any character][extra ignored]
2: 如果您的输入匹配以下
[可选空格][十进制数字*][可选空格][任何字符][额外忽略]
1: If your input failed above but matched the following
[Optional spaces][decimal digits*][Optional spaces][no more data]
1: 如果您的输入在上面失败,但匹配以下
[可选空格][十进制数字*][可选空格][没有更多数据]
[Correction]0: If your input, after white-space and an optional sign, did not find a digit: examples: "z"or "-".
[更正] 0:如果您的输入在空格和可选符号之后没有找到数字:examples:"z"或"-"。
EOF: If input was empty ""or only white-space.
EOF: 如果输入为空""或只有空格。
- The decimal digits may be preceded by a sign character
+or-.
- 十进制数字前面可以有符号字符
+或-.
回答by Dangling Cruze
You can always check what a function returns by putting it in a printfstatement like below :
您始终可以通过将函数放在printf如下语句中来检查函数返回的内容:
printf("%d",sscanf(string, " %d %c", &n, &c));
This will probably clear your doubt by printing out the return value of sscanfon your terminal.
这可能会通过sscanf在终端上打印出返回值来消除您的疑虑。
Also you can check this out : cplusplus : sscanf
你也可以看看这个:cplusplus:sscanf
Hope that helped :)
希望有所帮助:)

