Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using \ in a string as literal instead of an escape

bool stringMatch(const char *expr, const char *str) {   
    // do something to compare *(expr+i) == '\\'  
    // In this case it is comparing against a backslash
    // i is some integer
}

int main() {
    string a = "a\sb";
    string b = "a b";
    cout << stringMatch(a.c_str(), b.c_str()) << endl;
    return 1;
}

So the problem right now is: Xcode is not reading in the '\', when I was debugging in stringMatch function, expr appears only to be 'asb' instead of the literal a\sb'.

And Xcode is spitting out an warning at the line: string a = "a\sb" : Unknown escape sequence

Edit: I have already tried using "a\\sb", it reads in as "a\\sb" as literal.

like image 498
monkeyMoo Avatar asked Aug 24 '12 05:08

monkeyMoo


1 Answers

Xcode is spitting out that warning because it is interpreting \s in "a\sb" as an escape sequence, but \s is not a valid escape sequence. It gets replaced with just s so the string becomes "asb".

Escaping the backslash like "a\\sb" is the correct solution. If this somehow didn't work for you please post more details on that.

Here's an example.

#include <iostream>
#include <string>

int main() {
    std::string a = "a\\sb";
    std::cout << a.size() << ' ' << a << '\n';
}

The output of this program looks like:

4 a\sb

If you get different output please post it. Also please post exactly what problem you observed when you tried "a\\sb" earlier.


Regexs can be a pain in C++ because backslashes have to be escaped this way. C++11 has raw strings that don't allow any kind of escaping so that escaping the backslash is unnecessary: R"(a\sb)".

like image 80
bames53 Avatar answered Sep 22 '22 03:09

bames53