0

I'm using C++ and I have a problem. Instead of creating a new line it prints \n. My Code:

std::string text;

std::cout << text;

It prints:Hello\nWorld

It was supposed to read \n as a new line and print something like this:

"Hello
World"

So i've tried to use replace(text.begin(), text.end(), '\n', 'a') for testing purposes and nothing happened. It contiuned to print Hello\nWorld

  • Escape the new-line character. – Leaderboard Aug 09 '22 at 16:00
  • 6
    I think we need actual code. You're probably inexperienced, given your question, and it's unclear to me if you're talking about `std::string`, the type, or string literals (a C++ basic language construct) or something else. In `std::cout << "Hello, world \n"` the `\n` is a real newline character, – MSalters Aug 09 '22 at 16:01
  • 2
    If you see `\n` in some output, than the string literal is encoded as `\\n`, and you should replace the substring `"\\n"` with `"\n"`. – 273K Aug 09 '22 at 16:04
  • Oh, yes i'm talking about std::string. Sorry. – Thiago Prada Aug 09 '22 at 16:42
  • 3
    I recommend adding a [mre]. Currently your question can only be answered by guesses, and even if the guess is correct, it will be next to useless to the next asker with a similar problem. – user4581301 Aug 09 '22 at 16:43
  • I tested and `replace(str.begin(), str.end(), '\n', 'a');` works here with this [mcve]: [https://ideone.com/YscMSt](https://ideone.com/YscMSt) – drescherjm Aug 09 '22 at 17:05

1 Answers1

1

std::replace() won't work in this situation. When called on a std::string, it can replace only single characters, but in your case your string actually contains 2 distinct characters '\' and 'n'. So you need to use std::string::find() and std::string::replace() instead, eg:

string::size_type index = 0;
while ((index = str.find("\\n", index)) != string::npos) {
    str.replace(index, 2, "\n");
    ++index;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770