[英]how to reset stringstream object
我有一個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
}
如果你想每次循環一個新的ostringstream
對象,顯而易見的解決方案是在循環的頂部聲明一個新的ostringstream
對象。 所有ostream
類型都包含很多狀態,並且根據上下文,重置所有狀態可能或多或少都很困難。
如果要用其他東西替換stringstream
的內容,可以使用str()
方法。 如果你在沒有任何參數的情況下調用它,它將只獲得內容(正如你已經在做的那樣)。 但是,如果傳入一個字符串,那么它將設置內容,丟棄之前包含的內容。
例如:
std::stringstream os;
os.str("some text for the stream");
有關更多信息,請查看方法的文檔: http : //www.cplusplus.com/reference/sstream/stringstream/str
你的問題有點模糊,但代碼示例使它更清晰。
你有兩個選擇:
首先,通過構造初始化ostringstream(在循環的每個步驟中構造另一個實例):
for(int i = 0; i < 10; ++i) {
value = rand() % 100 ;
ostringstream os;
os << value;
cout << os.str() << " " << os << endl;
ntree->insert(os.str());
//i want my os object to initializ it here
}
其次,重置內部緩沖區並清除流狀態(錯誤狀態,eof標志等):
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 initializ it here
os.str("");
os.clear();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.