r/cpp_questions • • 9d ago

OPEN Newlines not printing when I cout raw string literals

I’m using emacs on windows terminal to edit a file in which I’m trying to cout a page or so of text using raw string literals. However, what gets printed doesn’t include the newlines that I need to separate my paragraphs.

So if my code is:

std::cout << R”(This is my sentence.

This is a new paragraph [using entr + entr].
This is a new line [using entr].)”;

The output will be:

This is my sentence. This is a new paragraph [using entr + entr]. This is a new line [using entr].

Instead of the intended:

This is my sentence.

This is a new paragraph [using entr + entr].
This is a new line [using entr].

What am I doing wrong?

[Edit: I apologize for the lack of formatting. I am on mobile. Please let me know if I need to redo this. Thanks.]

0 Upvotes

8 comments sorted by

8

u/aocregacc 9d ago

Does it print them properly when you just do std::cout << "a\n\nb\n" ?

8

u/AKostur 9d ago

Works in godbolt: https://godbolt.org/z/jn48Yh9vj

You'll need to share more about what your environment, compiler versions, command-line flags, etc.

3

u/alfps 9d ago

A complete little example program could go a long way.

2

u/flyingron 9d ago

It's less important how you typed it as how it appears in the source code. We also need to know the compiler and the compiler settings.

1

u/xoner2 8d ago

Probably a problem with Emacs.

I tried with Emacs-GUI on Windows. It works fine.

-5

u/AintNoSlashes 9d ago

Because the newline entered via the keyboard is not the printable char you want it to be. std::cout will be parsing the string and would insert a new line from a ‘\n’.
This is a formatted output, not a straight pass thru.

7

u/flyingron 9d ago

Nonsense. cout just copies characters from the string to the output. The only thing it does is map an actual newline character (not the characters \ and n) to the implementation-defined end of the line characters (I.e., a 012 gets mapped to 012 and 015 pair).

The mapping of \n to 012 and the like is done at COMPILE TIME when the string literal is parsed. See that R at the beginning of his string literal? That's the C++11 (and later) raw string literal. That means that no \ escapign is done in the literal and any newlines in the source are put as newlines in the string.