-1

I had an assignment of fractions in which the user sends input as a/b, but the a and b were simple integers and not negative or floats and extracting them was easy using if else statements

But right now I'm making a complex number (calculator type) program. And I'm actually taking a string in form of a + bi (where a and b can integer or float or both). I'm having difficulty how to go about without using a lot of extra lines.


Edited: My question was actually how to extract 'Real & Imaginary Part' from a + bi.

e.g. Input: 3.45 - 9.87 i and get float Real = 3.45 and float Imaginary = 9.87 out

I'm working in c++ and using visual studio

4

1 回答 1

0

iostreams 库提供了很好的重载运算符,您可以大致像这样读取表达式的组件:

string s = "3.45 - 9.87 i";
istringstream ist( s );
double re, im;
char op, ki;
ist >> re >> op >> im >> ki;
// op == '-'      
// ki == 'i'
complex<double> a( re, op == '-' ? -im : im );

从那里也应该很容易支持更灵活的表达式。

于 2013-11-17T12:23:54.760 回答