如何在字符串流中的位置书写

How to write at position in stringstream

本文关键字:位置 书写 字符串      更新时间:2023-10-16

我需要将char*缓冲区写入特定位置的std::stringstream,通过API读取,我设法组合了以下代码:

std::stringstream ss;
char * str = "123";
ss.seekp(0);
ss.write(str, 3);
ss.seekp(1);
ss.write(str, 3);
std::cout << ss.str(); //expecting 1123

然而,它并没有按预期工作——或者更准确地说,根本不工作(没有任何写入流),原因似乎是.seekp()


我只是设法证实了我的怀疑:在删除ss.seekp(0):后,.seekp()应该受到谴责

std::stringstream ss;
char * str = "123";
// remove this line: ss.seekp(0);
ss.write(str, 3);
ss.seekp(1);
ss.write(str, 3);
std::cout << ss.str(); //expecting 1123

它按预期打印1123。奇怪的是,在流上调用ss.seekp(0)会使其无法使用。有人能解释一下为什么会这样吗(c++文档中的一个来源)?

问题在于seekp参数:

ss.seekp(0)

告诉流相对于开始位置为0(即绝对值),但。。。流是空的,并且没有位置0。用更改

ss.seekp(0, std::ios_base::end);

这样它就起作用了。