Reputation: 532
I'm trying to do something like that:
#include <iostream>
std::string message = "Hello\r\"world\"";
int main() {
if (message[5] == '\\') {
switch (message[6]) {
case 'r':
std::cout << "\\r escape..." << std::endl;
break;
case '"':
std::cout << "\" escape..." << std::endl;
break;
}
}
return 0;
}
I know that logically it's right, but if you understood what I'm trying to do, you will notice that I want to know if there's a escape on the string. If the character is a escape, do what you see above (the switch).
Is that possible? Thank you.
Upvotes: 1
Views: 1771
Reputation: 66922
As Mike posted, string escapes are a way to type non-printable characters into a string in a programming language. The escapes themselves are not actually in the string with a \
. The character represented by '\n'
is what is in the string. Ergo, did you want something like this?
#include <iostream>
#include <cctype>
std::string message = "Hello\r\"world\"";
int main() {
switch (message[5]) {
case '\\': std::cout << "\\\\ escape...\n"; break;
case '\"': std::cout << "\\\" escape...\n"; break;
case '\'': std::cout << "\\\' escape...\n"; break;
case '\?': std::cout << "\\? escape...\n"; break;
case '\a': std::cout << "\\a escape...\n"; break;
case '\b': std::cout << "\\b escape...\n"; break;
case '\f': std::cout << "\\f escape...\n"; break;
case '\n': std::cout << "\\n escape...\n"; break;
case '\r': std::cout << "\\r escape...\n"; break;
case '\t': std::cout << "\\t escape...\n"; break;
case '\v': std::cout << "\\v escape...\n"; break;
case '\0': std::cout << "\\0 escape...\n"; break;
default:
if (isprint(message[5]))
std::cout << message[5] << " is not an escape...\n";
else {
std::cout << "\\x";
std::cout << std::hex << ((unsigned char)message[5]);
std::cout << " escape...\n" << std::dec;
}
break;
}
return 0;
}
There are also other escapes that have value parameters, and are not detectable in any manner, because they're not unique.
These are all identical after compilation
"\0a" //raw ASCII
"\n0\n141" //octal - ASCII
"\x0\x61" //hexidecimal - ASCII
"\u0061" //codepoint - UTF16
Upvotes: 2
Reputation: 91600
This is not possible. At runtime, you'll have the following bytes in the string:
The fact that this string constant happened to be created through escape sequences is completely irrellevent, as this is just compiler shorthand to create the above bytes. No where in memory will the backslash exist, thus there's no way at runtime to detect these escape sequences.
You could, of course, look to see if byte 6 was 13, or byte 7 was 34.
Upvotes: 5