c++coutconditional-operatorendl

Why can't I cout an endl in a conditional operator?


I am trying to print a comma-separated list of numbers by using a for loop, but I don't want there to be a comma after the last number, instead, I want there to be an endl.

I have this code:

for (int j = i; j > 0; j--) {
    // Should print 9, 8, 7, 6, 5, 4, 3, 2, 1[endl]
    cout << j << (j > 1 ? ", " : endl);
}

However, I get a compilation error

error: overloaded function with no contextual type information
    cout << j << (j > 1 ? ", " : endl);
                                 ^~~~

I have included iostream, endl works fine in other parts of the program, and replacing the endl with "\n" works fine...

I just want to know why this error occurs


Solution

  • endl is a function that adds a \n and then flushes the stream, it's not a string. Hence you can't use it in a ternary with another string as they don't have the same type.

    for (int j = i; j > 1; j--) {
        // Prints 9, 8, 7 ,6, 5, 4, 3, 2, 
        cout << j << ", ";
    }
    cout << 1 << endl;
    

    Of course, you need to handle the case where i is smaller than 1.

    The other option is to your "\n".