我有一个stringstream对象,我想知道如何初始化它.
stringstream os;
for(int i = 0; i < 10; ++i){
value = rand() % 100;
os<<value;
cout<<os.str()<<" "<<os<<endl;
ntree->insert(os.str());
//I want my os object to be reset here
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*nze 12
如果ostringstream每次循环都需要一个新对象,那么显而易见的解决方案是在循环顶部声明一个新对象.所有ostream类型都包含很多状态,并且根据上下文,重置所有状态可能或多或少都很困难.
如果要将stringstream其他内容替换为其他内容,可以使用该str()方法执行此操作.如果你在没有任何参数的情况下调用它,它将只获得内容(正如你已经在做的那样).但是,如果传入一个字符串,那么它将设置内容,丢弃之前包含的内容.
例如:
std::stringstream os;
os.str("some text for the stream");
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看方法的文档:http://www.cplusplus.com/reference/sstream/stringstream/str