简体   繁体   English

cin作为while循环中的条件?

[英]cin as a conditional in a while loop?

A bit new to C++ here. 这里有点新的C ++。 Is it possible to do something like the following? 有可能做以下事情吗?

int temp;
while(cin >> temp != -9999){//Do something with temp}

I can't get that exact code to work, but I feel like something such as that should be possible. 我无法使用那些确切的代码,但我觉得这样的事情应该是可能的。

Edit Tried the following as well: 编辑尝试以下内容:

while(cin.getline(temp) != -9999){//Do something with temp}

Still nothing. 依然没有。 Does getline() only work with strings? getline()只适用于字符串吗?

Yes, it does: 是的,它确实:

while (std::cin >> temp && temp != -9999)

However, operator precedence in C++ is annoying, so I would use: 但是,C ++中的运算符优先级很烦人,所以我会使用:

while (std::cin >> temp) {
    if (temp == -9999)
        break;

The reasoning is that std::cin is a stream. 原因是std::cin是一个流。 As such, reading from it returns the stream so you can do things like: 因此,从中读取会返回流,因此您可以执行以下操作:

std::cin >> temp >> temp2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM