istream::get(char&) 和 operator>> (char&) 的区别

Difference between istream::get(char&) and operator>> (char&)

我的问题似乎与this one相同,但我没有找到答案,因为原来的问题似乎问的更具体。 在C++98中,

有什么区别
char c;
cin.get(c);

char c;
cin >> c;

?

我查看了 get and operator>> 的 cplusplus 参考资料,它们对我来说是一样的。

我试过上面的代码,当我输入一个字符时,它们的行为似乎相同。

差异取决于流缓冲区中何时存在空白字符。

考虑输入“foo”

char c;
cin.get(c);

将在 c

中存储 ' '

不过

char c;
cin >> c;

将跳过空格并将 'f' 存储在 c

除了已经说过的之外,std::istream::get()也是一个未格式化的输入函数,所以 gcount() of the stream is affected, unlike the formatted extractor. Most of the overloads of get() and getline() have mostly been made obselete by the introduction of std::string, its stream extractors, and std::getline(). I'd say to use std::istream::get() whenever you need a single, unformatted character straight from the buffer (by using its single or zero argument overload). It's certainly quicker than turning off the skipping of whitespace first before using the formatted extractor. Also use std::string instead of raw character buffers and is >> str 用于格式化数据或 std::getline(is, str) 用于未格式化数据。