我已经尝试了好几种方法,

std::stringstream m;
m.empty();
m.clear();

这两种方法都行不通。


当前回答

m.str("");

似乎有用。

其他回答

我的观点是:

this seemed to work for me in xcode and dev-c++, I had a program in the form of a menu that if executed iteratively as per the request of a user will fill up a stringstream variable which would work ok the first time the code would run but would not clear the stringstream the next time the user will run the same code. but the two lines of code below finally cleared up the stringstream variable everytime before filling up the string variable. (2 hours of trial and error and google searches), btw, using each line on their own would not do the trick.

//clear the stringstream variable

sstm.str("");
sstm.clear();

//fill up the streamstream variable
sstm << "crap" << "morecrap";

在gnu c++中,这些函数不会丢弃stringstream中的数据

    m.str("");
    m.str() = "";
    m.str(std::string());

以下为我清空stringstream:

    m.str().clear();

这应该是最可靠的方式,不管编译器:

m=std::stringstream();

我一直在定义它的范围:

{
    std::stringstream ss;
    ss << "what";
}

{
    std::stringstream ss;
    ss << "the";
}

{
    std::stringstream ss;
    ss << "heck";
}

还有许多其他“有效”的答案,但它们通常会进行不必要的复制或重新分配内存。

交换流意味着您需要丢弃其中一个流,从而浪费内存分配。分配一个默认构造的流也是一样, 在字符串缓冲区中为字符串赋值(通过stringstream::str或stringbuf::str)可能会丢失字符串已经分配的缓冲区。

清除字符串流的规范方法是:

void clear(std::stringstream &stream)
{
   if (stream.rdbuf()) stream.rdbuf()->pubseekpos(0);
}

获取流缓冲区中数据大小的规范方法是:

std::size_t availSize() (const std::stringstream& stream)
{
   if (stream.rdbuf())
      return std::size_t(
         stream.rdbuf()->pubseekoff(0, std::ios_base::cur, std::ios_base::out));
   else
      return 0;
}

将数据从流复制到其他一些预先分配的缓冲区,然后将其清除的规范方法是:

std::size_t readAndClear(std::stringstream &stream, void* outBuf, std::size_t outSize)
{
   auto const copySize = std::min(availSize(stream), outSize);
   if (!copySize) return 0; // takes care of null stream.rdbuf()

   stream.rdbuf()->sgetn(outBuf, copySize);
   stream.rdbuf()->pubseekpos(0); // clear the buffer

   return copySize;
}

我希望这是一个规范的答案。语言律师,欢迎加入。