65,211
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <string>
using namespace std;
class Complex
{
friend istream & operator >>(istream & ,Complex & );
public:
double real;
double imag;
Complex(){real =0;imag = 0;}
};
istream & operator >>(istream & in,Complex & obj)
{
string num;
in>>num;
double R = 0;
double I = 0;
int flag1 = 0;//0 实部 1 虚部
int flag2 = 0;
int len = num.length();
char temp;
if(num[0] == 'i')
{
R = 0;
I = 1;
obj.real = R;
obj.imag = I;
}
else if(num[0] == '-')
{
if(num.find("i",1,1) == -1)//负实数
{
for(int i = 1;i < len;i++)
{
temp = num[i];
R = R * 10 + (temp - '0');
}
obj.real = - R;
obj.imag = I;
}
else
{
if(num.find("+",1,1) == -1 && num.find("-",1,1) == -1)//负虚数
{
for(int i = 1;i < len - 1;i++)
{
temp = num[i];
I = I * 10 + (temp - '0');
}
obj.real = R;
obj.imag = - I;
}
else
{
for(int i = 1;i < len - 1;i++)
{
temp = num[i];
if(temp == '+' || temp == '-')
{
flag1 = 1;
flag2 = (temp == '+')?0:1;
if(i == len -2)
{
I = 1;
}
}
else if(flag1 == 0)
{
R = R * 10 + (temp - '0');
}
else
{
I = I * 10 + (temp - '0');
}
}
obj.real = - R;
obj.imag = (flag2 == 0)?I:-I;
}
}
}
else
{
if(num.find("i",1,1) == -1)//正实数
{
for(int i = 0;i < len;i++)
{
temp = num[i];
R = R * 10 + (temp - '0');
}
obj.real = R;
obj.imag = I;
}
else
{
if(num.find("+",1,1) == -1 && num.find("-",1,1) == -1)//正虚数
{
for(int i = 0;i < len - 1;i++)
{
temp = num[i];
I = I * 10 + (temp - '0');
}
obj.real = R;
obj.imag = I;
}
else
{
for(int i = 0;i < len - 1;i++)
{
temp = num[i];
if(temp == '+' || temp == '-')
{
flag1 = 1;
flag2 = (temp == '+')?0:1;
if(i == len -2)
{
I = 1;
}
}
else if(flag1 == 0)
{
R = R * 10 + (temp - '0');
}
else
{
I = I * 10 + (temp - '0');
}
}
obj.real = R;
obj.imag = (flag2 == 0)?I:-I;
}
}
}
return in;
}
int main()
{
Complex a;
cin>>a;
cout<<a.real<<"+"<<a.imag<<"i"<<endl;
}
friend istream & operator >> (istream &, const complex & c) {
double a, b;
cin >> a;
cout << "+";
cin >> b;
cout << "i";
}