问题
How does std::cin
object deal with different types while it is an instance of basic_istream<char>
(istream
)?
回答1:
The class std::basic_istream<CharT, Traits>
models an input stream of characters of type CharT
. It provides both relatively low-level and relatively high-level access to that input stream. You can, for example, call std::cin.get()
in order to retrieve the next character from the input stream; this will always return CharT
, since that's the underlying type of characters in the stream. However, basic_istream
also provides the formatted input functions, whose purpose is to interpret that character stream as an encoding of some type, which could potentially be int
, std::basic_string<CharT, Traits>
, or something else. Thus, while the stream does not consist of int
s, there is an operator>>
that extracts an int
value by reading digits successively from a char
stream and interpreting them as the base-10 representation of an integer. The operator>>
function is overloaded so that it can be used to extract various different types.
来源:https://stackoverflow.com/questions/51055685/how-does-cin-object-converts-characters-to-different-types-as-user-needes