0

I have two issues here:

  1. 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.

  2. 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 <<
}
resolv
  • 47
  • 1
  • 1
  • 8

2 Answers2

0

I think one answer can be to write a std::streambuf and then use the std::streambuf in an inherited std::iostream

Community
  • 1
  • 1
0

If I understand correctly all you need to do is read the values directly into the data members:

istream& operator>>(istream& input, Complex& number)
{
    input.ignore(); // ignore the first (
    input >> number.real;
    input.ignore(); // ignore the ,
    input >> number.imaginary;
    input.ignore(); // ignore the next )

    return input;
}
David G
  • 94,763
  • 41
  • 167
  • 253
  • Gave this a shot. 2 errors, Complex::real is inaccessible. Complex::imaginary is inaccessible. – resolv Mar 22 '14 at 22:18