What values do the I/O operators (<< and >>) return?
来源:互联网 发布:新页erp网络破解版 编辑:程序博客网 时间:2024/05/17 04:20
What values do the I/O operators (<< and >>) return?
C++ allows you to define functions to associate with existing operators. The << and >> operators, whose orginal meanings were bitwise left and right shift, have additional meanings for C++ iostreams. So how do they work?The >> and << operators are evaluated left-to-right, so the following are equivalent statements, altho writing the parentheses would be rather weird.
cin >> a >> b >> c;(((cin >> a) >> b) >> c); // Same as above.What value is produced, for example, by
(cin >> a)
? And I mean what value is produced in the expression, not what value is read into the variable. It calls an overloaded templated function (operator>>
) in an istream
class which reads input and stores it into the variable on the right. It then returns the left operand (ie, cin
) so the result can be used if there is another >> operator. This chaining of the I/O operators is a rather clever solution. Here's an example program that shows this.if ((cin >> a) == cin) { cout << "Equal" << endl; // Yes, it is true } else { cout << "Not Equal" << endl; }
Why cin
can be used as a truth value
It's possible to make tests likeif (cin)which will be true if cin is ok and false if at an end-of-file or has encountered an error. It's type is
istream&
(input stream reference), so how can that be used as a truth value. The trick is that when it's evaluated in the context of a condition, eg, in an if
or while
statement, a special function is called in the istream
class. This function returns a value that can be interpreted as true or false.Reading in the while condition
Because the >> operator returns the iostream (eg, cin
), which can be tested for EOF or errors, the cin loop
idiom can be used.
while (cin >> x) { . . . }which effectively tests for EOF, and also that the input is a valid value.
- What values do the I/O operators (<< and >>) return?
- <eloquentjavascript>Values, Types, and Operators
- 输入输出运算符重载( Overloading the I/O operators)
- what-is-the-bios-and-what-does-it-do
- install a new linux operating system and the repeatable git bash (what I do after reinstall the sys)
- what should I do?
- What should i do?
- What should I do?
- what can i do?
- what can i do
- What shall I do?
- LOVE WHAT I DO
- What I do
- What should I do.
- What do I desire
- Why the Ban on P-Values? And What Now?
- What is a cronjob and how do I use it?
- What is a NullPointerException, and how do I fix it?
- 常用SQL时间格式
- sql STUFF用法
- 黑马程序员-C#中ToString格式大全
- 五个最好的屏幕录像软件
- String Matching: The Simple way to implement String Matching
- What values do the I/O operators (<< and >>) return?
- PPLIVE源代码泄露及两个struts命令执行漏洞
- 我的java思想002:为窗口增加窗口监听器类的三种方法
- 密码修改
- MFC双缓冲绘图
- Service初步
- 功率W与dBm的对照表及关系
- VC中调用matlab引擎
- 使用webmin安装管理vsftpd