How do you clear a stringstream variable?

后端 未结 8 1946
时光说笑
时光说笑 2020-11-22 13:53

I\'ve tried several things already,

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

both of which don\'t work.

相关标签:
8条回答
  • 2020-11-22 14:06

    It's a conceptual problem.

    Stringstream is a stream, so its iterators are forward, cannot return. In an output stringstream, you need a flush() to reinitialize it, as in any other output stream.

    0 讨论(0)
  • 2020-11-22 14:10

    This should be the most reliable way regardless of the compiler:

    m=std::stringstream();
    
    0 讨论(0)
  • 2020-11-22 14:13

    You can clear the error state and empty the stringstream all in one line

    std::stringstream().swap(m); // swap m with a default constructed stringstream
    

    This effectively resets m to a default constructed state

    0 讨论(0)
  • 2020-11-22 14:14

    I am always scoping it:

    {
        std::stringstream ss;
        ss << "what";
    }
    
    {
        std::stringstream ss;
        ss << "the";
    }
    
    {
        std::stringstream ss;
        ss << "heck";
    }
    
    0 讨论(0)
  • 2020-11-22 14:16

    These do not discard the data in the stringstream in gnu c++

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

    The following does empty the stringstream for me:

        m.str().clear();
    
    0 讨论(0)
  • 2020-11-22 14:21

    my 2 cents:

    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";
    
    0 讨论(0)
提交回复
热议问题