What exactly does stringstream do?

前端 未结 4 612
谎友^
谎友^ 2020-11-28 01:05

I am trying to learn C++ since yesterday and I am using this document:http://www.cplusplus.com/files/tutorial.pdf (page 32) . I found a code in the document and I ran it. I

4条回答
  •  囚心锁ツ
    2020-11-28 01:33

    To answer the question. stringstream basically allows you to treat a string object like a stream, and use all stream functions and operators on it.

    I saw it used mainly for the formatted output/input goodness.

    One good example would be c++ implementation of converting number to stream object.

    Possible example:

    template 
    string num2str(const T& num, unsigned int prec = 12) {
        string ret;
        stringstream ss;
        ios_base::fmtflags ff = ss.flags();
        ff |= ios_base::floatfield;
        ff |= ios_base::fixed;
        ss.flags(ff);
        ss.precision(prec);
        ss << num;
        ret = ss.str();
        return ret;
    };
    

    Maybe it's a bit complicated but it is quite complex. You create stringstream object ss, modify its flags, put a number into it with operator<<, and extract it via str(). I guess that operator>> could be used.

    Also in this example the string buffer is hidden and not used explicitly. But it would be too long of a post to write about every possible aspect and use-case.

    Note: I probably stole it from someone on SO and refined, but I don't have original author noted.

提交回复
热议问题