sscanf 行为/返回值 [英] sscanf behaviour / return value

查看:89
本文介绍了sscanf 行为/返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是学习 C 的新手,并试图从在线讲座中理解以下代码.它扫描一个字符串中的一个整数;如果遇到字符,sscanf 将失败.

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

我已经阅读了 sscanf 的手册页,但仍然对检查返回值以及此代码有效的原因感到困惑.他们声明这些函数返回分配的输入项的数量".

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 只遇到字符,它会将它们写入 &c...但在这种情况下 &n 不会被写入.在这种情况下,我会认为 sscanf 的返回值仍然是 1?

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 成功读取了 %d 并且没有别的,它将返回 1(一个参数已分配).如果数字前面有字符,它将返回 0 (没有分配参数,因为它需要首先找到一个不存在的整数).如果有一个带有附加字符的整数,它将返回 2,因为它能够分配两个参数.

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.

这篇关于sscanf 行为/返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆