scanf赋值不成功与出错的区别

 while(scanf("%d %d",&a,&b)!=EOF)
这里scanf赋值不成功时返回0,赋值出错时返回-1
那么什么时候算赋值不成功什么时候算赋值出错呢?

#悬赏#
全部评论
直接回答楼主的提问的话,你可以认为scanf是在输入流里做类似于正则表达式匹配一类的事(其实scanf也是支持正则表达式的),匹配到就解析一下塞进你指定的几个内存里,然后返回一个成功匹配的字符的个数作为返回值(这里成功匹配的个数为0也视为成功匹配,然后返回个0),如果读着读着输入流挂了,或者读取动作本身失败了,就算出错,返回EOF。 有的书喜欢用一些“作者自己读着方便”的话,比如说不成功和错误啥的,这种用法有时候对读者不太友好 ……
点赞 回复 分享
发布于 2018-11-26 22:55
遇到这种C语言函数/系统调用/过程调用的问题的时候,就在shell里man一下,仔细读读Linux Mannual。 比如说这个问题,man 3 scanf 然后输入/return 然后就会看到这么一段话:        On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.        The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs.  EOF is also returned if a read error occurs, in which  case  the        error indicator for the stream (see ferror(3)) is set, and errno is set to indicate the error. 你就知道啊原来读到结尾或者read出错就会返回EOF。那么什么时候read会出错呢? 我们知道C语言中具体的错误类型通常由一个线程局部变量errno标识,manual里面也会对库函数可能引发的错误作阐述。 然后你可以看看下面的errno的描述: ERRORS        EAGAIN The file descriptor underlying stream is marked nonblocking, and the read operation would block.        EBADF  The file descriptor underlying stream is invalid, or not open for reading.        EILSEQ Input byte sequence does not form a valid character.        EINTR  The read operation was interrupted by a signal; see signal(7).        EINVAL Not enough arguments; or format is NULL.        ENOMEM Out of memory.        ERANGE The result of an integer conversion would exceed the size that can be stored in the corresponding integer type. 你大概心里对哪些情况scanf会出错应该就有点想法了吧?
点赞 回复 分享
发布于 2018-11-26 22:42

相关推荐

07-17 11:50
门头沟学院 Java
投递腾讯等公司8个岗位
点赞 评论 收藏
分享
_mos_:忍耐王
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务