What exactly does stringstream do?

前端 未结 4 607
谎友^
谎友^ 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:35

    From C++ Primer:

    The istringstream type reads a string, ostringstream writes a string, and stringstream reads and writes the string.

    I come across some cases where it is both convenient and concise to use stringstream.

    case 1

    It is from one of the solutions for this leetcode problem. It demonstrates a very suitable case where the use of stringstream is efficient and concise.

    Suppose a and b are complex numbers expressed in string format, we want to get the result of multiplication of a and b also in string format. The code is as follows:

    string a = "1+2i", b = "1+3i";
    istringstream sa(a), sb(b);
    ostringstream out;
    
    int ra, ia, rb, ib;
    char buff;
    // only read integer values to get the real and imaginary part of 
    // of the original complex number
    sa >> ra >> buff >> ia >> buff;
    sb >> rb >> buff >> ib >> buff;
    
    out << ra*rb-ia*ib << '+' << ra*ib+ia*rb << 'i';
    
    // final result in string format
    string result = out.str() 
    

    case 2

    It is also from a leetcode problem that requires you to simplify the given path string, one of the solutions using stringstream is the most elegant that I have seen:

    string simplifyPath(string path) {
        string res, tmp;
        vector stk;
        stringstream ss(path);
        while(getline(ss,tmp,'/')) {
            if (tmp == "" or tmp == ".") continue;
            if (tmp == ".." and !stk.empty()) stk.pop_back();
            else if (tmp != "..") stk.push_back(tmp);
        }
        for(auto str : stk) res += "/"+str;
        return res.empty() ? "/" : res; 
     }
    

    Without the use of stringstream, it would be difficult to write such concise code.

提交回复
热议问题