How does cin object converts characters to different types as user needes?

孤者浪人 提交于 2021-02-05 12:27:06

问题


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 ints, 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!