[英]While scanf with boolean operator
I saw this piece of code today: 我今天看到了这段代码:
while(scanf("%d %d",&x,&y),x||y)
{
....
From what I've understand, it enters the loop if some of the values (x or y) is true. 根据我的理解,如果某些值(x或y)为真,它就会进入循环。
Since the scanf docs says: 由于scanf文档说:
On success, the function returns the number of items of the argument list successfully filled. 成功时,该函数返回成功填充的参数列表的项数。 This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file. 由于匹配失败,读取错误或文件结束的范围,此计数可以匹配预期的项目数或更少(甚至为零)。
I have rewritten the code to: 我已将代码重写为:
while(scanf("%d %d",&x,&y) >= 1)
{
....
But on an online programming challenge site the first while works, the second fails. 但是在第一个有效的在线编程挑战网站上,第二个失败了。
Am I right on my assumptions ? 我的假设是对的吗? What are the differences between this two pieces of code? 这两段代码有什么区别?
(I am tagging as C++, because I have tested in C++ 4.8.2 - GNU C++ Compiler) (我标记为C ++,因为我已在C ++ 4.8.2中测试过 - GNU C ++编译器)
scanf
returns the number of arguments it matches, but the first code fragment throws out that result and just checks to see if either x
or y
is true. scanf
返回它匹配的参数个数,但第一个代码片段抛出该结果,只检查x
或y
是否为真。 The second fragment returns that you matched at least one integer, regardless of value. 第二个片段返回您匹配的至少一个整数,无论值如何。
Consider the input "0 0"
. 考虑输入"0 0"
。 In the first case, scanf()
returns 2, but x || y
在第一种情况下, scanf()
返回2,但是x || y
x || y
returns false
. x || y
返回false
。 In the second case, your conditional is true
. 在第二种情况下,您的条件为true
。
The first code gives while
the result of x||y
, this is correct 第一个代码给出while
结果x||y
,这是正确的
However, the second code compares the return value of scanf
and 1
, and then gives while
the comparing result. 然而,第二码进行比较的返回值scanf
和1
,然后给出while
该比较结果。
run this code and you'll be clear. 运行此代码,你会很清楚。
#include<stdlib.h>
#include<iostream>
using namespace std;
int main()
{
int x, y;
cout<<(scanf("%d %d", &x, &y), x||y)<<endl;
cout<<(scanf("%d %d", &x, &y))<<endl;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.