getline in if statement

2019-05-07 19:10发布

From what I've read, getline() used in a Boolean context returns an implicitly conversion to void*. I haven't found anywhere on the web any real reference to this statement. Everywhere it says that implicit conversion doesn't exist and that in a Boolean context pointers should be of the same kind (and if ptr == 0 than 0 is converted to type of the pointer ptr).

Also in the standard says in a Boolean context it is converted to an unspecified-Boolean-type. What does that even mean?

2条回答
Lonely孤独者°
2楼-- · 2019-05-07 19:56

In short:

It means that you can use getline() in a if statement and if it works you enter the if statement block.

In Long:

getline() used in a Boolean context returns an implicitly conversion to void*.

The above is not technically correct (but that is the result). getline() actually returns a reference to the stream it was used on. When the stream is used in a Boolean context this is converted into a unspecified type (C++03) that can be used in a Boolean context. In C++11, this was updated and it is converted to bool.

  • If the getline() succeeded it returns a stream in a good state. When this is converted to a bool like type it returns a non-null pointer (C++03) which when used in a Boolean context is equivalent to true.
  • If the getline() fails it returns a stream in a bad state. When this is converted to a bool like type it returns a null pointer (C++03) which when used in a Boolean context is equivalent to false.

I haven't found anywhere on the web any real reference to this statement.

  • 21.4.8.9 Inserters and extractors [string.io]
    • Defines: std::istream& getline(std::istream&, std::string&)
  • 27.7.2.1 Class template basic_istream [istream]
    • Defines: std::istream& getline(char_type* s, streamsize n);
  • 27.5.5.1 Overview [ios.overview]
    • Defines how a stream is converted in a boolean context

Everywhere it says that implicit conversion doesn't exist and that in a Boolean context pointers should be of the same kind (and if ptr == 0 than 0 is converted to type of the pointer ptr).

A null void* in a Boolean context is equivalent to false, any other void* is equivalent to true. (though the type is actually unspecified but you can think of it as a void* (just to make it easy to think about).

Also in the standard says in a Boolean context it is converted to an unspecified-Boolean-type. What does that even mean?

It means you can use it any conditional statements:

if (getline())
{
     // If getline worked processes data
}

while(getline())
{
    // getline. If it works then processes then try again.
}
查看更多
手持菜刀,她持情操
3楼-- · 2019-05-07 20:01

It doesn't say it explicitly anywhere on the web because it involves putting three different facts together.

  1. getline() returns istream&
  2. istream is convertable to void*
  3. This conversion is used when an istream is used in boolean context (such as an if or while statement).
查看更多
登录 后发表回答