为什么while(std :: ifstream>> s)工作? [英] Why does while(std::ifstream >> s) work?

查看:250
本文介绍了为什么while(std :: ifstream>> s)工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的C ++编程中使用了很多语句:

  std :: string s; 
std :: ifstream in(my_input.txt);
if(!in){
std :: cerr<< 文件未打开<< std :: endl;
exit(1);
}
while(in>> s){
//使用s
执行操作}

我想知道的是,为什么会这样?



我看过<$ c的返回值$ c> operator>> ,它是一个 istream 对象,而不是布尔值。如果一个istream对象以某种方式如何解释为一个bool值,可以放在如果语句和 while 循环?

解决方案

基类 std :: basic_ios $ c> operator bool()方法返回一个表示流有效性的布尔值。例如,如果读取到达文件的结尾而没有抓取任何字符,则将在流中设置 std :: ios_base :: failbit 。然后将调用运算符bool(),返回!fail(),此时提取将停止,因为条件是false。



条件表达式代表显式布尔转换,因此:

  while(in>> s)



  while(static_cast< bool>(in>> s))

这相当于

  while((> ; s).operator bool())

这相当于

  while(!(in>> s).fail())

I've used statements such as this quite a bit in my C++ programming:

std::string s;
std::ifstream in("my_input.txt");
if(!in) {
    std::cerr << "File not opened" << std::endl;
    exit(1);
}
while(in >> s) {
    // Do something with s
}

What I want to know is, why does this work?

I looked at the return value of operator>>, and it's an istream object, not a boolean. How does an istream object somehow get interpreted as a bool value that can be put inside of if statements and while loops?

解决方案

The base class std::basic_ios provides an operator bool() method that returns a boolean representing the validity of the stream. For example, if a read reached the end of file without grabbing any characters, then std::ios_base::failbit will be set in the stream. Then operator bool() will be invoked, returning !fail(), at which time extraction will stop because the condition is false.

A conditional expression represents an explicit boolean conversion, so this:

while (in >> s)

is equivalent to this

while (static_cast<bool>(in >> s))

which is equivalent to this

while ((in >> s).operator bool())

which is equivalent to

while (!(in >> s).fail())

这篇关于为什么while(std :: ifstream&gt;&gt; s)工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆