gpt4 book ai didi

c++ - 当 std::stringstream 使用 ("some content"构造时,tellg() 的预期行为是什么,std::ios::in|std::ios::ate)?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:37:05 27 4
gpt4 key购买 nike

我有以下令我惊讶的代码(使用 libstdc++4.8)...

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

int main() {
std::string s("some content");
std::stringstream ss(s, std::ios::in|std::ios::ate);
std::istream& file = ss;
//ss.clear(); Makes no difference...
std::cout << "tellg() pos: " << file.tellg() << std::endl;
return 0;
}

...具有以下输出。

tellg() pos: 0

此行为与使用 std::ifstream(std::ios::ate) 时不同。

  • 此行为是否正确/符合预期?
  • 尽管用 ate 打开,是否需要显式 seekg(0, std::ios::end)?
  • 清除状态并没有什么不同。
  • 请注意字符串有内容

最佳答案

这完全符合标准告诉我们的内容。以下是相关详细信息:

您使用的构造函数版本:

Constructs a std::basic_stringbuf object by calling the default constructor of std::basic_streambuf, initializes the character sequence with an empty string, and sets the mode to which, than followed by initializing the associated character sequence as if by calling str(new_str).

basic_stringbuf 的默认构造函数在这里并不有趣,而且比 std::basic_stringbuf::str:

Deletes the entire underlying character sequence of this std::basic_stringbuf and then configures a new underlying character sequence containing a copy of the contents of s. ... For append streams (mode & ios_base::ate == true), pptr() == pbase() + s.size(), so that subsequent output will be appended to the last character copied from s

最后,tellg(),它在缓冲区上调用 pubseekoff:

If which includes ios_base::in and this buffer is open for reading (that is, if ((which & ios_base::in) == ios_base::in), then repositions the read pointer std::basic_streambuf::gptr: .. then newoff is the current position of the pointer (gptr()-eback() in this case)

总结一下:因为你没有以任何方式修改 get 位置(构造函数只修改 put 位置),它返回 0。

关于c++ - 当 std::stringstream 使用 ("some content"构造时,tellg() 的预期行为是什么,std::ios::in|std::ios::ate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36427129/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com