输入虚数的表达式,分离实部和虚部并输出。-C++

读入一个字符串,该字符串为一个虚数,如何分离出该虚数的实部和虚部呢? 下面为笔者的拙见

/*
两个函数介绍:
    strchr(char *,char);该函数返回字符串中指向从第二个参数字符开始的指针,若该字符串没有该字符,则返NULL
    atof(char *);将字符串转化为浮点数,函数会从左往右依次扫描,从第一个数字或正负号开始,到第一个不为数字或者.为止
*/
#include<iostream>
#include<cstring>//strchr()
#include<cstdlib>//stof()
using namespace std;
class complex
{
          
   
	double real,imag;
public:
	complex(double r=0,double i=0):real(r),imag(i){
          
   }
	complex & operator =(const char *s);
	void print();
};
complex &complex::operator =(const char *s)//s最好不动
{
          
   
	int len;
	if(s)
	{
          
   
		len=strlen(s);
		char *stmp=new char [len+1];
		strcpy(stmp,s);
		
		char *p=strchr(stmp,+);//strchr函数返回stmp内从‘+’开始的一个指针,若没有该字符,返回NULL
		real=atof(s);
		imag=atof(p);
		delete []stmp;
	}
	else
	{
          
   
		real=0;
		imag=0;
	}
	return *this;
}
void complex::print()
{
          
   
	cout<<real<<"+"<<imag<<"i"<<endl;
}
int main()
{
          
   
	complex c;
	c="3+4i";
	c.print();
	return 0;
}
经验分享 程序员 微信小程序 职场和发展