【问题标题】:std::stringstream buffer manipulationstd::stringstream 缓冲区操作
【发布时间】:2014-08-12 05:45:54
【问题描述】:

我正在将一些数据放入从 stringstream 获得的流 buf 中

std::stringstream data;
auto buf = data.rdbuf();
buf->sputn(XXX);

我想要的是能够将一些虚拟数据放入此缓冲区,然后在以后获得正确数据后,替换虚拟数据。

以下几行:

auto count = 0;
buf->sputn((unsigned char *)&count, sizeof(count));
for (/*some condition*/)
{
   // Put more data into buffer

   // Keep incrementing count
}

// Put real count at the correct location

我尝试使用 pubseekpos + sputn,但它似乎没有按预期工作。任何想法可能是正确的方法吗?

【问题讨论】:

    标签: c++ stringstream streambuf


    【解决方案1】:

    只需使用data.seekp(pos);,然后使用data.write() - 您根本不需要使用缓冲区。

    【讨论】:

      【解决方案2】:

      这可能会帮助您入门,它会写入一些X 并将它们打印回来,这也可以通过data << 'X' 完成:

      #include <sstream>
      #include <iostream>
      int main() {
          std::stringstream data;
          auto buf = data.rdbuf();
          char c;
          for (int count = 0; count < 10; count++) {
              buf->sputn("X", 1); 
          }   
          while (data >> c) {
              std::cout << c;
          }   
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-10
        • 1970-01-01
        • 2014-03-31
        • 2011-04-16
        • 1970-01-01
        相关资源
        最近更新 更多