C++ 如何重置stringstream对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17743903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 21:24:44  来源:igfitidea点击:

how to reset stringstream object

c++stringstream

提问by realtekme

I have a stringstream object and I am wondering how to reset it.

我有一个 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
    }

回答by James Kanze

If you want a new ostringstreamobject each time through the loop, the obvious solution is to declare a new one at the top of the loop. All of the ostreamtypes contain a lot of state, and depending on context, it may be more or less difficult to reset all of the state.

如果ostringstream每次循环都需要一个新对象,显而易见的解决方案是在循环顶部声明一个新对象。所有ostream类型都包含很多状态,并且根据上下文,重置所有状态可能或多或少困难。

回答by Peter Bloomfield

If you want to replace the contents of the stringstreamwith something else, you can do that using the str()method. If you call it without any arguments it will just getthe contents (as you're already doing). However, if you pass in a string then it will setthe contents, discarding whatever it contained before.

如果你想stringstream用其他东西替换 的内容,你可以使用str()方法来做到这一点。如果你不带任何参数调用它,它只会获取内容(正如你已经在做的那样)。但是,如果您传入一个字符串,那么它将设置内容,丢弃之前包含的任何内容。

E.g.:

例如:

std::stringstream os;
os.str("some text for the stream");

For more information, check out the method's documentation: http://www.cplusplus.com/reference/sstream/stringstream/str

有关更多信息,请查看该方法的文档:http: //www.cplusplus.com/reference/sstream/stringstream/str

回答by utnapistim

Your question is a bit vague but the code example makes it clearer.

您的问题有点含糊,但代码示例使其更加清晰。

You have two choices:

你有两个选择:

First, initialze ostringstream through construction (construct another instance in each step of the loop):

首先,通过构造初始化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
}

Second, reset the internal buffer and clear the stream state (error state, eof flag, etc):

其次,重置内部缓冲区并清除流状态(错误状态、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();
}