-1
void printAst(int x)
{
    for( int i = 0; i < x; i++)
    {
        cout << "*";
    }
    cout << " (" << x << ")" << endl;
}

void printHisto(int histo[])
{
    //cout.precision(3);

    int count = 0;

    for(double i = -3.00; i < 3.00; i += 0.25)
    {
        cout << setprecision(3) << i << " to " << i + 0.25 << ": " << printAst(histo[count]) << endl;
        // cout << setw(3) << setfill('0') << i << " to " << i + 0.25 << ": " << histo[count] << endl;
        count ++;
    }
}

I want my output to be formatted like this, so I used setprecision(3), which also does not work.

-3.00 to -2.75: (0)
-2.75 to -2.50: * (1)
-2.50 to -2.25: * (1)
-2.25 to -2.00: * (6)
-2.00 to -1.75: ***** (12)

So instead it is formatted like this

-3 to -2.75: 3
-2.75 to -2.5: 4
-2.5 to -2.25: 5
-2.25 to -2: 0
-2 to -1.75: 0

The main problem however, is that when I try to call printAst on to histo[count]. This is what is causing this error. PrintAst is used to print the asteriks, histo[count] provides the amount of asteriks to print.

cout << setprecision(3) << i << " to " << i + 0.25 << ": " << printAst(histo[count]) << endl;

stateless
  • 246
  • 1
  • 7

1 Answers1

0

You seem to have a misunderstanding about how chaining << works in streams.

cout << 42 looks like an operator expression with two operands, but it's really a call to a function with two parameters (the name of the function is operator<<). This function returns a reference to the stream, which enables the chaining.

An expression like this:

cout << 1 << 2;

is equivalent to this:

operator<<( operator<<(cout, 1), 2);

Now, the problem is that a parameter to a function can't be void but that's what printAst returns. Instead, you need to return something that can be streamed - in other words, something that operator<< is already overloaded for. I'd suggest std::string:

std::string printAst(int x);
{
    std::string s = " (" + std::string(x,'*') + ")";
    return s;
}

You can read more about operator overloading.

Community
  • 1
  • 1
jrok
  • 54,456
  • 9
  • 109
  • 141