简体   繁体   中英

ignore escape sequence c++

I have tried searching google but could not find answer, can anyone tell that how to ignore escape character stored in string . I am using an array which holds different characters like this

string str[]={"| | / / ||","| |/ / ||", "| | ( \ \ \ \`_."}

Error message from compiler:

"unknown escape sequence" at

As @Zac has already pointed out, you can escape the \\ to avoid the problem. Another way you may find cleaner 1 would be to use raw string literals:

string str[]={R"(| | / / ||)",R"(| |/ / ||)", R"(| | ( \ \ \ \`_.)"};

Since it's not apparent from that sample, I'll point out one additional detail: if your strings might contain a ) character, you can add more delimiters before the opening parenthesis, that also have to be matched next to the closing parenthesis, something like this:

string s = R"!(This (might be) an MS-DOS path\to\a\string)!";

Edit: Oh, one other minor detail: a raw string literal produces the same type of result as a normal string literal. You can intermix the two freely. For example, I could have left the first two literals above as normal literals, and only made the third one raw, since it's the only one that contains a backslash. For initializing an array (or other collections), I prefer to make them all raw if any of them is going to be, but that's strictly personal preference for the sake of consistency, not something the language requires.


1. Just in case: this is new with C++ 11, so if you're using an older compiler, this may not be supported.

You must escape the \\ character. Your string would look like this:

string str[]={"| | / / ||", "| |/ / ||", "| | ( \\ \\ \\ \\`_."};

In C++ (and most other C-based langauges), \\ is used to indicate an escape character (eg \\r , \\n , \\t , etc). If you want to have an actual "\\" character in your string, you must escape it: \\\\ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM