blitzeus
blitzeus

Reputation: 495

overloaded stream extraction operator

im trying to input a complex number and use an overloaded operator to handle parsing the real and imaginary parts. If I enter a number like 1 + 2i, i want real = 1 and imaginary = 2.

Right now if I enter 1 + 2i enter, output is 1 + 0i. How can I do this properly (Number has private data members real and imaginary and operator>> is a friend function)

//input the form of 1 + 2i
istream & operator>>(istream &in, Number &value)
{    
    in >> std::setw(1) >> value.real;
    in.ignore(3); //skip 'space' and '+' and 'space'
    in >> std::setw(1) >> value.imaginary;
    in.ignore(); //skip 'i'

    return in;
}


//output in the for 1 + 2i
ostream &
operator<<(ostream &out, const Complex &value)
{
    out << value.real << " + " << value.imaginary << "i" <<std::endl;

    return out;
}

Upvotes: 0

Views: 466

Answers (1)

Rufflewind
Rufflewind

Reputation: 8956

Your code works just fine on my compiler! Perhaps the issue is elsewhere (e.g. in the output)?

Do note that std::setw has no effect when extracting numbers from the input stream.

Remember that you may also want to consider cases of the form: A - Bi and possibly if the user decides to insert extra or remove spaces around the operator or the i. But for the simple case A + Bi your prototype shouldn't be an issue.

Upvotes: 1

Related Questions