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

前端 未结 3 1280
逝去的感伤
逝去的感伤 2021-01-18 05:29

In an example given in C++ Primer,

#include 
using namespace std;

int main() {
    int sum = 0, value = 0;  
    while (std::cin >> va         


        
相关标签:
3条回答
  • 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.

    0 讨论(0)
  • 2021-01-18 06:14

    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)

    0 讨论(0)
  • 2021-01-18 06:15

    If you are a beginner you don't need to write

    std::


    everytime. If you have written:

    using namespace std;


    it would do the trick. I hope you got the point. :)

    0 讨论(0)
提交回复
热议问题