Rust println! problem - weird behavior inside the println macro [duplicate]

若如初见. 提交于 2021-01-29 17:50:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!