How do I parse \n from a string?

I'm trying to get a string from user which contains escape characters like \n and others. But, after getting user input, when I try to print that exact string to standard output via print macro it prints literal \n instead of a newline.

Here's my code:

use std::io::{self, Write};

fn main() {
    let mut string = String::new();
    io::stdin().read_line(&mut string);
    print!("{}", string);
    io::stdout().flush().unwrap();
}

Output:

~ ./main
are you working \n\n ???
are you working \n\n ???

When you input a string such as "hello\n", it corresponds to something like let input = String::from("hello\\n"). Hence, the \n is literally present.
You can do a input.replace("\\n", "\n").

1 Like

that works; but if I wanna check for \t and other escape characters then do I have chain .replace again and again or there is other method?

That is one way. The other way may be to manually iterate through the string bytes, and change escape characters in one go.

1 Like