问题
I am currently working on a simple "user input" program. The user can enter a number, which I get with
std::io::stdin().read_line(&mut let_name_here).ok().expect("Error");
. After getting the user input I want to print it to the console for a review.
I have noticed strange behavior within the println! macro. The following code
println!("Your input: {}", let_name_here);
println!("Your input: {}", let_name_here);
outputs this:
Your input: 15
Your input: 15
Why is there an extra \n
in the println!
marco. From my coding experience I would assume the following:
Your input: 15
Your input: 15
But to achive this output I have to use folloing code:
print!("Your input: {}", let_name_here);
print!("Your input: {}", let_name_here);
I don't understand why the println!
marco outputs\n
twice. What would I do, if I want to \n
at the end of the first line, with those two marcos it would not be possible. Am I missing something important?
回答1:
It looks like there is a newline character at the end of the string you have read from stdin. The println macro is then adding a newline char to the end resulting in two newlines.
You should strip away the newline character from the end of the text read from stdin, or just use print if you don't want to do that.
来源:https://stackoverflow.com/questions/58039413/rust-println-problem-weird-behavior-inside-the-println-macro