0

I want the following printout to appear in the my screen when I run my code:

\begin{tabular}

\hline \\

For that, I am using the following command on my code:

std::cout<<"\begin{tabular}<< std::endl;

std::cout<<"\hline \\"<< std::endl;

And I'm getting the following compiler message (regarding the second line of code):

unknown escape sequence: '\h'

and the following incomplete printout:

egin{tabular}

hline\

Where in the first one the "\b" is missing and the first and last \ are missing for the second sentence.

The question is: does anyone know how I can print the \ symbol as text, such that it will get printed and not be interpreted as a command, etc?

jotNewie
  • 426
  • 4
  • 17
  • 6
    You need to check out [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and find a good beginners book or tutorial, because the meaning of backslash in string and character literals should be extremely basic knowledge. – Some programmer dude Jul 27 '15 at 12:02
  • 3
    Ironically, you have just faced this problem: in your original post you had to type the `\\` 3 times (it should actually be 4) in order to have it displayed twice. That's because they are escaped. Now somebody has edited your post by adding the code formatting, which disables the escape, so we all see 3 backslashes instead of 2. C++ does the same thing as this site. – Fabio says Reinstate Monica Jul 27 '15 at 12:21
  • 1
    Thanks for your point, Fabio, I just edited the post so that the \ is only seen twice as intended. – jotNewie Jul 28 '15 at 12:24

4 Answers4

7

The backslash forms escape sequences in C++. You have two options:

  1. Double all the backslashes, a la "\\hline \\\\" (the backslash will escape itself, just as in TeX).
  2. Use C++11 raw strings, which look like R"(\hline \\)" (the text is enclosed by the parens inside the quotes).
Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
2

Just escape it wiht '\'. So if you want to print out '\' character you must do:

cout<<'\\'<<endl;
gandgandi
  • 330
  • 1
  • 8
2

Use double backslash (\) if you would like to print \ as a character in your output, otherwise, single \ followed by some character has inherent meaning of some special character, e.g. \n for newline, \r for carriage return \t for tab etc

Dr. Debasish Jana
  • 6,980
  • 4
  • 30
  • 69
2

Double all the backslashes. e.g.

std::cout<<"\\hline \\\\"<< std::endl;

backslash is an escape code in C++. As in, below, the "\"escape sequence and n is escape code. Which means a newline character.

"hello\n"

so if you want to print \ as well, you need to escape it too.

"hello\\hi"
Nishant
  • 1,635
  • 1
  • 11
  • 24