Search code examples
c++iostreamline-breakscoutcompiler-explorer

Why does "std::cout << char() << std::endl;" not even print a new line on Compiler Explorer?


This code:

#include <iostream>

int main() {
    std::cout << "---" << std::endl;
    std::cout << char() << std::endl;
    std::cout << "---" << std::endl;
}

prints this:

---
---

Why isn't std::endl causing a new line to be between the other two?

Removing char() << makes the output become what I expect:

---

---

Solution

  • The code will cause the standard library to print a null character followed by a newline character to the stream.

    How these characters are presented to you is a matter of the terminal or other UI you are using to view the stream's contents.

    I would normally expect a terminal to skip the null character as non-printable and to interpret the newline as usual. However, I don't think there is any kind of standard or specification requiring this behavior.

    In this concrete case I suspect a bug in how compiler explorer presents the output, probably in AnsiToHtml that is based on https://github.com/rburns/ansi-to-html and used to format output of the compiler containing ANSI escape codes. The library does some tokenization of the input, so a bug of this kind doesn't seem unlikely, but I don't know enough JavaScript/TypeScript to figure this out with a quick look.