istringstream::str() 没有 return 当前内容

istringstream::str() does not return current contents

我有一个 istringstream,我正在将一些数据放入其中。然后,我提取一些我输入的数据,然后我想得到istringstream剩余的内容。我认为,显然是错误的,以下内容可以做到这一点:

std::istringstream stream("Two words");
std::string word;
stream >> word;
std::cout << word << std::endl;
std::cout << stream.str() << std::endl;

输出为:

Two words
Two
Two words

换句话说,提取操作正在返回正确的值,并且它正在推进读指针,如 tellg 所示,但 str 似乎并不关心——它只是returns istringstream 的全部原创内容。 我确定这是预期的行为,但我就是不明白为什么。

所以:我怎样才能轻松干净地获取 istringstream 的剩余内容,为什么 str 还没有这样做?

and why isn't str doing it already?

我相信有些人会想要一种方式,而另一些人会想要另一种方式。

how can I easily and cleanly get the remaining contents of the istringstream>

这并不难。使用:

std::cout << stream.str().substr(stream.tellg()) << std::endl;

why isn't str doing it already?

因为这是此方法的 documented 行为:

Returns a copy of the underlying string as if by calling rdbuf()->str().

它总是returns整个底层字符串

how can I easily and cleanly get the remaining contents of the istringstream

只需将您的代码更改为:

std::cout << stream.rdbuf() << std::endl;

live example

输出为:

Two
 words