i have a code for complex number but when i key in 7+i3 and 5+i2 into the operator+ it should return me the result of 12,5 but i receive 430. What is the problem wif my code?

class Complex
{
	friend istream& operator>>(istream&, Complex&);
	friend ostream& operator<<(ostream&, const Complex&);
public:
	Complex(int, int);		// constructors
	Complex operator +(Complex);
private:
	int a, b;	
};

Complex::Complex( int _a=0, int _b=0 ) 
{
   a = _a;
   b = _b;
}


istream& operator>>(istream &in, Complex &num)
{
    string line="";
    in>>line;
    for(int i=0; i<line.length(); i++)
    {
            if(i==1)
            {
                 num.a = line[i];
            }
            else if(i==4)
            {
                 num.b = line[i];
            }     
    }         
	return in;
}

ostream& operator<<(ostream &out, const Complex &num)
{
    out<<num.a;
    out<<num.b;
    return out;         
}

Complex Complex::operator +(Complex t)
{
    Complex temp;
    temp.a = a + t.b;
    return temp;       
}

int main()
{
    Complex A, B, C;
    cout << "Enter first complex number, format (a+ib): ";
    cin >> A;
    cout << "Enter second complex number, format (a+ib): ";
    cin >> B;

    C = A + B;
    cout << "Addition A + B = " << C << endl;
    system("pause");
    return 0;
}

>out<<num.a;
>out<<num.b;
First I'd suggest you separate those two values with something. Your actual output is 43,0.

if(i==1)
{
  num.a = line[i];
}

At position 1 in "7+i3" is '+'. So the first problem is that you're assigning the wrong character. The second problem is that you're assigning the value of the character and not the value of the digit it represents. So even if you change that test to i == 0 , you'll still get (most likely) 55 instead of 7. For single digits you can subtract '0' from the digit to get the proper value:

if ( i == 0 )
{
  num.a = line[i] - '0';
}

Rinse and repeat.

This article has been dead for over six months. Start a new discussion instead.