Hi i've have this problem in my code when i do the overloading of operator >>. My problem for this code isnt encounter error but my input like say i input 7, the num.a output will change this 7 to 55 and num.b output for 5 to 53. below is the code.

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

private:
	int a, b;	
};

istream& operator>>(istream &in, Complex &num)
{
    string line="";
    fflush(stdin);
    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;
}

my format of input is (7+i3). This is a complex number format. Hope to hear the reply soon.Thanks

Step by step.

1. Don't fflush(). There is no need and you shouldn't be mixing C and C++ I/O anyway.

2. You are mis-indexing the string: 01234 7+i3 Hence, line[1] == '+' and line[4] == '\0'. BTW, i never reaches 4 if your input is only four characters long.

3. You are not converting your numbers. The ASCII value of '+' is 43.

4. Your constructor should look like this: Complex( int _a=0, int _b=0 ): a( _a ), b( _b ) {}; or Complex( int _a=0, int _b=0 ) { a = _a; b = _b; } The first way is preferred.
The reason num.b is some weird number is because your constructor never initializes the private fields a and b. Having arguments with the same name makes no difference.

PS. Complex numbers are normally written a + bi. If you do the same you will have an easier time collecting and verifying input.

Hope this helps.

Thanks alot. actually my problem lies with the line thing, like you have explain. It turn out to be taken as ASCii '7' instead of int '7' thats y it output to 55. I actually did my changes by adding line - 48 to it to make it back to '7'. Really thanks alot abt the constructor thing.

> actually did my changes by adding line - 48 to it to make it back to '7'. line[i] - '0' would be much better; you program would then be not dependant on a particular character encoding.

Thanks alot for this '0' didnt realise can do it this way.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.