如何使用cout输出 \ 符号?

12

如何在cout输出中输出\符号?

7个回答

28

使用两个反斜杠 \\


24
除了所有正确的答案,还可以参考以下内容获取更多转义字符。
\a  Bell (beep)
\b  Backspace
\f  Formfeed
\n  Newline
\r  Return
\t  Tab
\\  Backslash
\'  Single quote
\"  Double quote
\xdd    Hexadecimal representation
\ddd    Octal representation
\?  Question mark ('?')

你错过了几个。另外,'\m'(即非特殊字符)会发生什么? - Martin York

16

'\'字符在C和C++中被视为转义字符。如果想要输出一个 '\' 字符,可以使用双反斜杠来进行转义:

'
   cout << "This is a backslash: \\";

4
也许。
cout << "\\";

4
std::cout << '\\';

4
自 C++11 起,您还可以使用原始字符串字面量
std::cout << R"(There is no need to escape backslash here \)";

转义字符(如\n、\t或")在原始字符串字面量中不会被处理。

1
cout << "\\" << endl;

你可以使用除 endl 以外的方式:

cout << "\\ \n";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接