Superex
Superex

Reputation: 199

How does while (std::cin >> value) work?

In an example given in C++ Primer,

#include <iostream>
using namespace std;

int main() {
    int sum = 0, value = 0;  
    while (std::cin >> value) {       
        sum += value; // equivalent to sum = sum + value
    }    
    std::cout << "Sum is: " << sum << std::endl;    
    return 0; 

}

How does (std::cin >> value) return true? And what is an "End Of File"? It seems that I must understand that term in order to understand my primary question.

Thanks!

Upvotes: 7

Views: 2555

Answers (2)

Edwin Rodr&#237;guez
Edwin Rodr&#237;guez

Reputation: 1257

C++ translates this line

while (std::cin >> value)

to something like

inline bool f(int v) {
  auto& i = std::cin >> v;
  return i.operator bool();
}

while( f(v) ) {

Why it translates to bool? Because while expects a boolean expression, so compiler search for the boolean conversion operator of the return of std::cin >> v.

What is a bool conversion operator? Boolean conversion operator translates the object to bool. If some part of the code expect to some type to work a as boolean (like casting) then this operator is used.

What is an operator? Is a function or method that override the behavior of some operationg expressions (+, -, casting, ->, etc)

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

The overloaded operator>> function returns a reference to the stream itself, and the stream have an overloaded operator that allows it to be used in a boolean condition to see if the last operation went okay or not. Part of the "okay or not" includes end of file reached, or other errors.

Upvotes: 9

Related Questions