0

I have a problem with printing my class. I want this class to read a binary number and then print it. I am a Beginner, so here can be a really dumb mistake. This code has a wrong output, but a correct input. I tried to fix this, but I couldn't. I hope you will find the mistake. Please help. Thanks!

Here is the code:

#include <iostream>

using namespace std;

class Binary
{
    int len;
    bool* arr;

public:
    Binary();
    Binary(const Binary&);

    friend istream& operator >> (istream&, Binary&);
    friend ostream& operator << (ostream&, const Binary&);
};


Binary::Binary()
{
    len = 0;
    arr = new bool[0];
}

Binary::Binary(const Binary& b)
{
    len = b.len;
    arr = new bool[len];
    for (int i = 0; i < len; i++) {
        arr[i] = b.arr[i];
    }
}

istream& operator>>(istream& in, Binary& b)
{
    char line[101];
    in.getline(line, 100);

    b.len = strlen(line);
    b.arr = new bool[b.len];

    for (int i = 0; i < b.len; i++) {
        b.arr[i] = (line[i] == '0' ? 0 : 1);
    }

    return in;
}

ostream& operator<<(ostream& out, const Binary& b)
{
    for (int i = 0; i < b.len; i++) {
        out << b.arr;
    }
    return out;
}

int main() {
    Binary a;
    cin >> a;
    cout << a;

    return 0;
}

1 Answers1

1

The problem is with this line of code:

        out << b.arr;

You are printing the array pointer, b.arr, instead of a value in the array.

This will work:

        out << b.arr[i] ? '1' : '0';

You should also consider writing a destructor to free your previously allocated memory, and also free the previous array before overwriting it's pointer on this line:

b.arr = new bool[b.len];
DutChen18
  • 1,133
  • 1
  • 7
  • 24