关于C++中的字符串流

About stringstreams in C++

本文关键字:字符串 C++ 关于      更新时间:2023-10-16

在学习面试问题时,我在互联网上看到了这段代码:

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加号"+"?(,然后是虚部ia,然后再次读取buff(也许是为了n? 我的理解正确吗? 但是,如果我删除缓冲区,它适用于像1+2i这样的输入,但在虚部像1+-2i这样的负数时失败(是的,不是1-2i(。

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

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

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

是的,你的理解是正确的。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

因此,通过添加对单个字符的显式读取,您可以在第 2 个operator >>中读取"+",并且可以在 3rst 调用中正确读取"3"或"-3"operator >>