加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

scanf是否保证不会在失败时更改值?

发布时间:2020-12-16 03:37:56 所属栏目:百科 来源:网络整理
导读:如果scanf系列函数无法与当前说明符匹配,是否允许写入存储成功值的存储? 在我的系统上,以下输出213两次但是有保证吗? 标准中的语言(C99或C11)似乎没有明确指出原始值应保持不变(无论是否不确定). #include stdio.hint main(){ int d = 213; // matching fa
如果scanf系列函数无法与当前说明符匹配,是否允许写入存储成功值的存储?

在我的系统上,以下输出213两次但是有保证吗?

标准中的语言(C99或C11)似乎没有明确指出原始值应保持不变(无论是否不确定).

#include <stdio.h>

int main()
{
    int d = 213;

    // matching failure
    sscanf("foo","%d",&d);
    printf("%dn",d);

    // input failure
    sscanf("",d);
}

解决方法

C11标准的相关部分是(7.21.6.2,对于fscanf):

7 A directive that is a conversion specification defines a set of matching input sequences,as described below for each specifier. A conversion specification is executed in the following steps:

8 […]

9 An input item is read from the stream,unless the specification includes an n specifier. An input item is defined as the longest sequence of input characters which does not exceed any specified field width and which is,or is a prefix of,a matching input sequence.285) The first character,if any,after the input item remains unread. If the length of the input item is zero,the execution of the directive fails; this condition is a matching failure unless end-of-file,an encoding error,or a read error prevented input from the stream,in which case it is an input failure.

10 Except in the case of a % specifier,the input item (or,in the case of a %n directive,the count of input characters) is converted to a type appropriate to the conversion specifier. If the input item is not a matching sequence,the execution of the directive fails: this condition is a matching failure. Unless assignment suppression was indicated by a *,the result of the conversion is placed in the object pointed to by the first argument following the format argument that has not already received a conversion result. […]

对我来说,单词“step”和“如果输入项的长度为零,指令的执行失败”表示如果输入与格式中的说明符不匹配,则解释在该说明符的任何赋值之前停止发生了.

另一方面,关于引用的子条款4清楚地说明了指定失败者的说明符,再次使用适合于有序事件序列的语言:

4 The fscanf function executes each directive of the format in turn. When all directives have been executed,or if a directive fails (as detailed below),the function returns.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读