wirly
wirly

Reputation: 33

How to read a backslash as part of a string in C++

I am trying to read a backslash as part of a string, but it is always escaped.

For example:

string s = "Bo\nes"

for(int i = 0; i < s.size(); i++) {
    if (s[i] == '\\') cout << "Found a backslash";
}

That does not work. And across other testing I always get the string reading as "Boes". How would I be able to read that backslash such that I can parse the entire string?

Upvotes: 1

Views: 2405

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 596352

In a string/character literal, \n is an escape sequence for a line feed (decimal 10, hex 0x0A), and \\ is an escape sequence for a single \ character (decimal 92, hex 0x5C).

Thus, in the string literal "Bo\nes", there is no \ character in the string. It contains these characters:

B o \n e s (0x42 0x6F 0x0A 0x64 0x73)

Not these characters, like you are expecting:

B o \ n e s (0x42 0x6F 0x5C 0x6E 0x64 0x73)

That is why if (s[i] == '\\') (aka if (s[i] == 0x5C)) is always false.

You need to escape the \ in \n to accomplish what you want:

string s = "Bo\\nes";

Then the literal will contain the characters you are expecting.

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 310990

Here are examples

std::string s1 = "Bo\\nes";
std::string s2 = R"(Bo\nes)";

That is either you have to use the escape sequence '\\' for the backslash character or a raw string literal.

Here is a demonstrative program.

#include <iostream>

int main() 
{
    std::string s1 = "Bo\\nes";
    std::string s2 = R"(Bo\nes)";
    
    std::cout << "\"" << s1 << "\"\n";
    std::cout << "\"" << s2 << "\"\n";
    
    return 0;
}

Its output is

"Bo\nes"
"Bo\nes"

Another way is to use an octal or hexadecimal escape sequence like for example

std::string s = "Bo\134nes";

or

std::string s = "Bo\x5Cnes";

Upvotes: 6

R Sahu
R Sahu

Reputation: 206607

You'll have to escape the backslash in the original string.

string s = "Bo\\nes";

Otherwise, there is no backslash character in the string to compare against.

Upvotes: 5

Related Questions