It is necessary to replace all the characters in the line / \\ . Did as follows:

 string s; cin >> s; for(int i = 0; i < s.size(); i++) { if(s[i] == '/') { s.replace(i, 1, "\\"); } } 

But for some reason it turns out that the symbol / is replaced only with \ , and not with \\ .

    3 answers 3

    The fact is that "\\" is a single bekslesh. Try "\\\\" .


    In C ++, in string literals \ is a special escape character: it does not mean itself, but simply modifies the value of the character following it. For example, \n means not Bexlesh and the character n , but a newline, a character with the code 0x10.

    Therefore, by itself, bexlesh does not mean bexlesh. To enter bekslesha you need to use \\ .

    You can check the length of the string "\\\\" , it is equal to 2. (Check: http://ideone.com/DhxHe8 )


    This, by the way, is probably the reason for the editor’s strange behavior towards double bekslesh.

    • Yes, it worked. And why? - IWProgrammer
    • @RomaMikov: Added the answer. - VladD
    • This is not only in C ++, but in many places. Almost standard de facto. - 0andriy

    Write like this:

     s.replace(i, 1, "\\\\"); 
    • Yes, it worked. And why? - IWProgrammer
    • one
      Because the \ character is the beginning of the control sequence β€” well, as in \n , for example. Accordingly, to represent the symbol \ itself, the control sequence \\ is used. - Harry
    • And if there are a lot of slashes and there are too many lines to replace, and they are also very long? - avp
    • 2
      Then use raw string literals (see, for example, here ) - Harry

    Or so:

     s.replace(i, 1, R"(\)");