I have two issues here:
I am trying to overload the istream operator >> to accept an input of "(a, b)" and set a = real and b = imaginary. I can skip the first ( with input.ignore(), but the number entered can be any size so I am not sure how to read just "a" up to the comma into real and just b into imaginary.
When I try to set number.real, I get the error member Complex::real is inaccessible.
header
class Complex
{
friend istream &operator>>(istream &, Complex &);
friend ostream &operator<<(ostream &, const Complex &);
private:
double real;
double imaginary;
};
source
#include <iostream>
#include <string>
#include <iomanip>
#include "complex.h"
using namespace std;
Complex::Complex(double realPart, double imaginaryPart)
:real(realPart),
imaginary(imaginaryPart)
{
}
istream &operator>>(istream &input, Complex &number)
{
string str;
int i = 0;
input >> str;
while (str[i] != ','){
i++;
}
input.ignore(); // skips the first '('
input >> setw(i - 1) >> number.real; //?? "Enter a complex number in the form: (a, b)
}
main
#include <iostream>
#include "Complex.h"
using namespace std;
int main()
{
Complex x, y(4.3, 8.2), z(3.3, 1.1), k;
cout << "Enter a complex number in the form: (a, b)\n? ";
cin >> k; // demonstrating overloaded >>
cout << "x: " << x << "\ny: " << y << "\nz: " << z << "\nk: "
<< k << '\n'; // demonstrating overloaded <<
}