1

I am trying to save in a char the symbol "\" and later print it but I can't.

Any good idea?

char direction = '\';
printf("%c", direction);
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

3 Answers3

9

Escape it.

char direction = '\\';
simondvt
  • 324
  • 3
  • 13
9

You can directly print like this:

printf("\\");

for print any special character.

\\ - Backslash
\' - Single Quotation Mark
\" - Double Quotation Mark
\? - Question Mark
\n - New line
\r - Carriage Return
\t - Horizontal Tab
\b - Backspace
\f - Formfeed
\a - Bell (beep sound)
\v - Vertical Tab

ref : https://stackoverflow.com/a/11792217/5747242

C11 §6.4.4.4 Character constants and §5.2.2 Character display semantics also help.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Jignasha Royala
  • 1,032
  • 10
  • 27
  • I can never remember if \a is universally supported or is an option. Note also that `\?` is needed optionally for `?` to escape trigraphs. – Bathsheba Nov 01 '18 at 12:03
  • 2
    The alert (`'\a'`) has been standard C since the beginning, @Bathsheba. It vies with `\v` for the "least useful escape sequence" trophy. – Jonathan Leffler Nov 01 '18 at 12:04
  • @JonathanLeffler, and `\?` too surely? I shall endeavour to remember `\a` being standard from now on. – Bathsheba Nov 01 '18 at 12:05
  • @Bathsheba: The `\?` has a purpose because of trigraphs — which are ignored by most people and many compilers. For example, if you write `printf("What??!\n");`, you should see `What|` on the output if your compiler heeds trigraphs — and `What??!` if it doesn't. GCC requires `-trigraphs` to pay attention to them. The standard says it should happen all the time. I believe C++ finally said "there are no trigraphs any more". To get the sequence I wanted, in Standard C (with trigraphs), I'd write `printf("What\?\?!\n");` — though only one of the two `\?` sequences is sufficient. – Jonathan Leffler Nov 01 '18 at 12:08
  • @JonathanLeffler: Indeed, trigraphs are removed from C++17. Sad time indeed for the obfsucators. My understanding is that in C, trigraphs are substituted before the preprocessor. – Bathsheba Nov 01 '18 at 12:09
  • 2
    @Bathsheba: C11 [§5.1.1.2 Translation phases](https://port70.net/~nsz/c/c11/n1570.html#5.1.1.2): Trigraphs are removed when newlines are added in Step 1 — so that backslash-newline processing can proceed in Step 2, etc. – Jonathan Leffler Nov 01 '18 at 12:14
2

You have to use '\\'. The backslash it's the escape character.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
zediogoviana
  • 305
  • 3
  • 14