gpt4 book ai didi

c++ - std::stringstream 是否有两个缓冲区,因此有两个标记?

转载 作者:行者123 更新时间:2023-12-03 23:40:05 24 4
gpt4 key购买 nike

关于 C++ 入门第 17 章; I/O 流;据说类型为 std::iostream 的对象或派生类型,如 std::fstream , std::stringstream支持阅读和写作。这些类型也只有一个标记和一个缓冲区:

The fstream and stringstream types can read and write the same stream. In these types there is a single buffer that holds data to be read and written and a single marker denoting the current position in the buffer. The library maps both the g and p positions to this single marker.


所以为了了解更多我已经完成了这个程序:
int main(){


std::fstream fio("data.txt");
std::cout << fio.tellg() << '\t' << fio.tellp() << '\n';
fio.seekg(0, std::ios::end);
std::cout << fio.tellg() << '\t' << fio.tellp() << '\n';

std::stringstream ss("abcd\nefg\nhi\nj");
std::cout << ss.tellg() << '\t' << ss.tellp() << '\n';
ss.seekg(0, std::ios::end);
std::cout << ss.tellg() << '\t' << ss.tellp() << '\n';

}
输出:
 0      0
14 14
0 0
13 0
  • 正如您在使用 std::fstream 时所见如果我使用 seekg() 移动读取标记然后是 tellgtellp返回相同的值。这是非常合乎逻辑的。
  • 但是,当移动 std::stringstream 的读取标记时, tellgtellp返回不同的值所以写标记没有被移动?
  • 这是否意味着 std::stringstream有两个缓冲区和两个标记?谢谢
  • 最佳答案

    是的,书错了。
    std::basic_filebuf它同步读取和写入位置,并且,

    the class template basic_fstream implements high-level input/output operations on file based streams. It interfaces a file-based streambuffer (std::basic_filebuf) with the high-level interface of (std::basic_iostream).


    然而,基类, std::basic_streambuf , 确实保持独立的输入和输出缓冲区。注意

    the I/O stream objects std::basic_istream and std::basic_ostream, as well as all objects derived from them (std::ofstream, std::stringstream, etc), are implemented entirely in terms of std::basic_streambuf.

    关于c++ - std::stringstream 是否有两个缓冲区,因此有两个标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66307281/

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