Anne Quinn
Anne Quinn

Reputation: 13040

What are acceptable custom escape characters for use within C++ string literals

I want to embed certain signals within a string literal in the same style as "\n" and "\a". My program looks at the string, sees the escape character, and then acts depending on the character following it.

The problem however is that C++, as part of it's compilation process, resolves anything using "\" as the escape character. In addition, the C standard library, which I use frequently, uses "%" as an escape character too.

So both "\" and "%" can't be used. The forward slash "/" looks too similar to "\", and for the moment, most other characters are either too commonly used, or do not give the appearance of an escape.

My question is, what is the best character to use as an escape character, that does not collide with common C++ string utilities that rely on their own escaping character. "Best" in this sense, would objectively describe a character that is used infrequently in normal dialog and mathematics, and is readily identifiable as an escape at a glance.

Upvotes: 0

Views: 2101

Answers (4)

Joseph Mansfield
Joseph Mansfield

Reputation: 110778

There's no reason why you can't escape your backslashes (e.g. \\n). If you find that ugly to type, try raw string literals from C++11:

R"(hello\nfriend\a\b\c\d)"

Note that the parentheses are not part of the string. If your string is going to contain )" you can put your own delimiter before the opening parenthesis, which must follow the closing paranthesis:

R"delim(hello\nfriend\a\b)"something)delim"

Upvotes: 5

melpomene
melpomene

Reputation: 85907

My favorite alternative escape character is ` (backtick). Why? Because it doesn't occur often in normal text, C and C++ don't use it at all, and it looks like a tiny backslash.

Upvotes: 2

Thomas
Thomas

Reputation: 182093

bash uses $ to insert variables into a string:

"Hello $name! How are you?"

Windows cmd uses % for the same:

"Hello %name%! How are you?

C# uses {} for string formatting:

String.Format("Hello {0}! How are you?", name)

Any of those would readily be recognizable.

Upvotes: 0

KamikazeCZ
KamikazeCZ

Reputation: 724

I suppose you can normally use '\' as long as you save it into the string as two characters, for example '\' and 'n' rather than '\n'.

Upvotes: 0

Related Questions