-3

How do I assign the value of '\' to a character variable?

C++ doesn't recognize the backslash as a character and thinks there should be a 't' or 'n' or something afterwards.

How can the \ be assigned to a char variable?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Noa Vidović
  • 17
  • 1
  • 2

2 Answers2

4

You need to escape it properly: '\\'

mindriot
  • 5,413
  • 1
  • 25
  • 34
4

The backslash character is used as 'escape' sign for characters like '\"' or '\'' to give them a special meaning for their appearance in literals instead of closing the literal.

There's also a number of escaped character values with more special meanings like e.g. '\n', that expands to a new line in output.

To give the special meaning for the \ character, it must be escaped itself:

char c = '\\';
       // ^
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190