关于C ++中的stringstreams

时间:2017-07-24 14:44:35

标签: c++ stringstream

在研究面试问题时,我在网上看到了这段代码:

class Solution {
public:
    string complexNumberMultiply(string a, string b) {

        //I initially did it using substring (searching for "+" etc.)
        //But it is super easy using stringstreams

        stringstream aa(a), bb(b), ans;
        int ra, rb, ia, ib;
        char buff;
        aa>>ra>>buff>>ia>>buff;
        bb>>rb>>buff>>ib>>buff;

        ans<<ra*rb-ia*ib<<"+"<<ra*ib+rb*ia<<"i";
        return ans.str();
    }
};

此代码段将两个输入字符串相乘,表示a+bi形式的复数。因此,如果输入为1+1i1+1i,则此代码生成的输出为0+2i(因为i^2=-1)。

我理解为什么使用了字符串流aabb以及它们如何工作;但我不理解char buff的作用。请考虑以下声明:

aa>>ra>>buff>>ia>>buff;

在这里,我们首先从字符串流aa读取理性部分ra(然后buff获取加号&#34; +&#34;?),然后是虚部ia然后再次buff(也许是\n?)。我的理解是否正确?如果我删除了缓冲区,它对1+2i之类的输入工作正常,但在假想部分为负的情况下失败,如1+-2i(是的,不是1-2i)。

如果我的理解是正确的,请告诉我。谢谢!

2 个答案:

答案 0 :(得分:3)

你几乎是对的。当你有一个像1+1i这样的字符串时,你有两个有效的整数和两个有效字符。因此,aa>>ra会将第一个整数读入ra,并将+1i留给您。然后>>buff将字符(+)读入buff,并在流中留下1i。然后>>ia读取下一个整数并在流中留下i。然后>>buff会消耗流中的i消息。

通常在做这样的事情时,我喜欢使用更具描述性的变量名称。我喜欢使用eater,因为这意味着我只是在吃输入(扔掉它)。如果我知道输入会是什么样子,那么更具描述性的名称就像sign / operator / imaginary_part一样好。

答案 1 :(得分:0)

是的,您的理解是正确的。 operator >>对于每个输入流(std::istream的祖先)都是通用的,并且它使用std::num_get::get作为整数。

对第2阶段逻辑和正虚部aa >> ra >> rb的编码将如下运行:

2 -> accumulated to storage "2" 
     (because 2 matches one of "0123456789abcdefxABCDEFX+-")
+ -> ignored, because "2+" is not valid integer for scanf, so first
     operator >> terminates here
+ -> accumulated to storage "+"
3 -> accumulated to storage "+3"
i -> ignored, because "+3i" is not a valid integer, so we 
     can scan "+3" as integer 3 and put it to rb

第二个整数的负虚部被破坏:

+ -> accumulated to storage "+"
- -> "+-" is not a valid scanf, so we should terminate second 
     operator >> while putting 0 to ra because "+" is also is not 
     an integer

因此,通过添加单个字符的明确阅读,您可以阅读&#39; +&#39;在第二operator >>中,可以阅读&#34; 3&#34;或&#34; -3&#34;正确地在第一次调用operator >>

相关问题