I am performing a complex number using operator overloading. In the program, the user enters a complex number ALWAYS in the form:
a + bi
So in the example ...
25.0 + 3.6i
Assume that the user will always enter both the real and imaginary parts of the complex number, for example, the user enters "5 + 0i" (rather than "5") or "0 - 6.2i" (and not "-6.2i").
My problem is that in main () I have the following code:
ComplexNumber c1;
cin >> c1;
cout << c1;
and the code prints:
0 + 0i
... when I entered "4.2 + 8.3i" at the run-time prompt.
Here is my implementation of my class operator>>:
istream & operator>>(istream & in, ComplexNumber & n) {
string real;
string imag;
bool done = false;
int sign = 1;
string num;
in >> num;
int length;
for (int i = 0; i < num.length(); i++) {
if (num.at(i) == 'i') {
imag = num.substr((i - length), i);
}
else if (num.at(i) == '-') {
sign = -1;
}
else if (num.at(i) == ' ') {
if (!done) {
real = num.substr(i);
done = true;
}
length = 0;
}
length++;
}
n = ComplexNumber(atof(real.c_str()), atof(imag.c_str()) * sign);
return in;
}
Here is my class implementation operator<<:
ostream & operator<<(ostream & out, const ComplexNumber & n) {
n.print(out);
return out;
}
Here is my implementation of the ComplexNumber print () member class:
void ComplexNumber::print(ostream & out) const {
if (imag >= 0)
out << real << " + " << imag << "i";
else
out << real << " - " << (-1 * imag) << "i";
}
This is the ComplexNumber header file for more details:
#ifndef COMPLEXNUMBER_H
#define COMPLEXNUMBER_H
#include <iostream>
using namespace std;
class ComplexNumber {
public:
ComplexNumber();
ComplexNumber(double real_part, double imaginary_part);
ComplexNumber(const ComplexNumber & rhs);
void print(ostream & out = cout) const;
bool equals(const ComplexNumber & rhs) const;
const ComplexNumber & operator=(const ComplexNumber & rhs);
const ComplexNumber & operator+=(const ComplexNumber & rhs);
const ComplexNumber & operator-=(const ComplexNumber & rhs);
const ComplexNumber & operator*=(const ComplexNumber & rhs);
private:
double real;
double imag;
};
ComplexNumber operator+(const ComplexNumber & lhs, const ComplexNumber & rhs);
ComplexNumber operator-(const ComplexNumber & lhs, const ComplexNumber & rhs);
ComplexNumber operator*(const ComplexNumber & lhs, const ComplexNumber & rhs);
bool operator==(const ComplexNumber & lhs, const ComplexNumber & rhs);
bool operator!=(const ComplexNumber & lhs, const ComplexNumber & rhs);
ostream & operator<<(ostream & out, const ComplexNumber & n);
istream & operator>>(istream & in, ComplexNumber & n);
#endif
.