Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cin as a conditional in a while loop?

Tags:

c++

cin

A bit new to C++ here. 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?

like image 473
Soatl Avatar asked Sep 13 '26 11:09

Soatl


1 Answers

Yes, it does:

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

However, operator precedence in C++ is annoying, so I would use:

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

The reasoning is that std::cin is a stream. As such, reading from it returns the stream so you can do things like:

std::cin >> temp >> temp2;
like image 76
Cole Tobin Avatar answered Sep 15 '26 00:09

Cole Tobin