-4

When I try to do printf("----/");, the \ is removed from the output

#include <iostream>

int main() {
    std::cout << ("Welcome to the game\n\n");

    printf("--------\n");
    printf("----O---\n");
    printf("---/|\--\n");
    printf("---/-\--\n");
}

output:

--------
----0---
---/|--
---/---
Enlico
  • 23,259
  • 6
  • 48
  • 102
  • 3
    Question: are you expecting the ``\`` that precedes the `n` to print out? (Hopefully not.) Why not? Why should that backslash be special, but the person's left arm and leg not be special? – JaMiT Jun 18 '22 at 04:24
  • Try using `---/-\\--` – Alexander Jun 18 '22 at 04:27

2 Answers2

2

The \ character is a special one, it's the escape character. You can write special things with it (like \n for new line). Because this character is special, writing it to console requires using \\.

Libertas
  • 358
  • 2
  • 5
  • 11
0

The answer has been given already: \ is special, because it's the escape character, and you need to escape it with itself if you want a literal \ in the outoupt.

This, however, can make the drawing confused.

To improve the things, you can use raw strings literals

    printf(R"(--------
----O---
---/|\--
---/-\--)");

Notice that I've truly inserted a line break in place of the \n escape sequence, because \n would be literally interpreted as a \ followed by the letter n.

Clearly, you can still have issues, if a string contains exactly the characters )", because it will be detected as the closing token of the string:

//               +---- code invalid from here
//               |
//               v
printf(R"(-----)"---)");

but you can still solve it, for instance by adding another set of wrapping "s:

printf(R""(-----)"---)"");

or anything else in between the " and (, and between ) and " (not symmetrized):

printf(R"xyz(-----)"---)xyz");
//                        ^
//                        |
//                        +--- not zyx
Enlico
  • 23,259
  • 6
  • 48
  • 102