问题
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?
回答1:
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 tovoid*
.
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 abool
like type it returns a non-null pointer (C++03) which when used in a Boolean context is equivalent totrue
. - If the
getline()
fails it returns a stream in a bad state. When this is converted to abool
like type it returns a null pointer (C++03) which when used in a Boolean context is equivalent tofalse
.
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
than0
is converted to type of the pointerptr
).
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.
}
回答2:
It doesn't say it explicitly anywhere on the web because it involves putting three different facts together.
- getline() returns istream&
- istream is convertable to void*
- This conversion is used when an
istream
is used in boolean context (such as anif
orwhile
statement).
来源:https://stackoverflow.com/questions/8204113/getline-in-if-statement