0

I noticed that the raw string literal uses '\n' for line endings. I would like to change it to "\r\n", How do i do that? Im using Visual Studio 2022.

    std::string req = R"(line 1
line 2
line 3
)";

    for (size_t i = 0; i < req.size(); i++)
    {
        if (req[i] == '\n') {
            std::cout << "\\n";
        }
        else if (req[i] == '\r') {
            std::cout << "\\r";
        }
        else {
            std::cout << req[i];
        }
    }

The output is line 1\nline 2\nline 3\n Is it possible to make it line 1\r\nline 2\r\nline 3\r\n

ihsan
  • 145
  • 2
  • 10
  • The raw string literal uses whatever is in the literal. – tkausl Apr 20 '22 at 12:34
  • 1
    @tkausl doesn't seem to in MSVC at least, in a file saved with CRLF line endings the literal does indeed only contain LFs, see https://stackoverflow.com/questions/39885423/c-is-there-a-standard-definition-for-end-of-line-in-a-multi-line-string-const – Alan Birtles Apr 20 '22 at 12:37
  • Please show a [example] that illustrates your issue. – JohnFilleau Apr 20 '22 at 12:48
  • You could always 1) explicitly include the `\r\n` as a newline group of characters, and 2) write your string in multiple lines, as shown here: https://godbolt.org/z/KKaP6ffPG. – rturrado Apr 20 '22 at 21:47
  • @rturrado no, yours not work https://godbolt.org/z/GGEqK5MGf – apple apple Apr 21 '22 at 04:38
  • @appleapple I don't see any difference between your link and mine, apart from the fact that you have added a `std::cout << req << '\n';` – rturrado Apr 21 '22 at 09:50
  • @rturrado it means there is no new line char in your string. – apple apple Apr 22 '22 at 05:51
  • @appleapple there is, but it is a raw string, so if you print it you just get unprocessed `\r\n` in the output. The important thing is that the `for` block processes the string correctly. – rturrado Apr 22 '22 at 09:17
  • @rturrado well, what I want to say is, do you realise `if (req[i] == '\n') { std::cout << "\\n"; }` is never executed in your example? Definitely not what OP want. – apple apple Apr 22 '22 at 14:24
  • 1
    @appleapple ohhh, I see! Sorry I didn't notice until now. Thanks for your comments and your explanation! – rturrado Apr 22 '22 at 14:27
  • 1
    @rturrado no problem :) actually it's a good suggestion, just don't use raw string literal https://godbolt.org/z/PoWh1bTcG – apple apple Apr 22 '22 at 14:40
  • it can also mixed with raw string literal https://godbolt.org/z/W8M3veYx5. (to some point it may be easier to just do a replace though) – apple apple Apr 22 '22 at 14:43

0 Answers0