c++ using stringstream


  • 23
    B

    stringstream is very useful to extract num from a string

    class Solution {
    public:
        string complexNumberMultiply(string a, string b) {
            int ra, ia, rb, ib;
            char buff;
            stringstream aa(a), bb(b), ans;
            aa >> ra >> buff >> ia >> buff;
            bb >> rb >> buff >> ib >> buff;
            ans << ra*rb - ia*ib << "+" << ra*ib + rb*ia << "i";
            return ans.str();
        }
    };

  • 0
    B

    @beetlecamera thank you for the wonderful solution. I had a quick question - what exactly is the use of buff? stringstream itself will split the string on the basis of "+" and "\n", so why exactly are you using buff? Thanks.


  • 1
    B

    @BatCoder said in c++ using stringstream:

    @beetlecamera thank you for the wonderful solution. I had a quick question - what exactly is the use of buff? stringstream itself will split the string on the basis of "+" and "\n", so why exactly are you using buff? Thanks.

    buff is the char used to hold '+' char
    for the input with negative image part, it would be something like 123+-123i, when you do aa >> ra, the pos flag inside of aa would point to +, so you need a buff to take the char +, otherwise aa>>ia would be 0


  • 0
    B

    @beetlecamera And is the last buff used to hold a \n?


  • 1
    B

    @BatCoder said in c++ using stringstream:

    @beetlecamera And is the last buff used to hold a \n?

    it is i, C++ string does not end with '\0'. and actually you do not need the second buff
    also you can put 2 input string together, stringstream ss(a+b), a and b would be separated by char i, then you can do ss >> ra >> buff >> ia >> buff >> rb >> buff >> ib, but I feel like 2 lines are easier to read. The first and third buff is +, and the second buff is i


  • 0
    B

    @beetlecamera This is very helpful. Thank you! :)


  • 0
    S

    Not that it is very important here, but it is generally recommended to separate the input and output string streams. Just a comment.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.