while(cin)和while(cin>> num)之间的区别是什么 [英] What's the difference between while(cin) and while(cin >> num)

查看:214
本文介绍了while(cin)和while(cin>> num)之间的区别是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个循环之间的区别是什么?每个循环何时停止?

What the difference between the following two loops and When each one will stopped ?

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
    int x,y;
    while(cin >> x){
        // code
    }
    while(cin){
        cin >> y;
        //code
    }
    return 0;
}


推荐答案

while(cin >> x) {
    // code
}

这个循环直观地表示从 cin into x ,只要一个值可以读取,继续循环。一旦读取的值不是 int ,或者一旦 cin 关闭,循环终止。这意味着只有 x 有效时才会执行循环。

This loop, intuitively, means "keep reading values from cin into x, and as long as a value can be read, continue looping." As soon as a value is read that isn't an int, or as soon as cin is closed, the loop terminates. This means the loop will only execute while x is valid.

另一方面, / p>

On the other hand, consider this loop:

while(cin){
    cin >> y;
    //code
}

语句 while (cin)意味着 cin 上的所有操作都成功,继续循环。一旦我们进入循环,我们将尝试读取一个值到 y 。这可能会成功,否则可能会失败。然而,不管是哪种情况,循环将继续执行。这意味着一旦输入无效数据或没有更多数据要读取,循环将使用 y 的旧值再执行一次,因此您将有一个

The statement while (cin) means "while all previous operations on cin have succeeded, continue to loop." Once we enter the loop, we'll try to read a value into y. This might succeed, or it might fail. However, regardless of which one is the case, the loop will continue to execute. This means that once invalid data is entered or there's no more data to be read, the loop will execute one more time using the old value of y, so you will have one more iteration of the loop than necessary.

你应该肯定喜欢这个循环的第一个版本到第二个版本。除非有有效数据,否则它从不执行迭代。

You should definitely prefer the first version of this loop to the second. It never executes an iteration unless there's valid data.

希望这有助于!

这篇关于while(cin)和while(cin&gt;&gt; num)之间的区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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