生锈的println!问题-println宏内的行为异常 [英] Rust println! problem - weird behavior inside the println macro

查看:70
本文介绍了生锈的println!问题-println宏内的行为异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个简单的用户输入"程序.用户可以输入一个我得到的数字 std :: io :: stdin().read_line(&mut let_name_here).ok().expect("Error"); .收到用户输入后,我想将其打印到控制台进行审查.

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.

我注意到println内有奇怪的行为!宏.以下代码

I have noticed strange behavior within the println! macro. The following code

println!("Your input: {}", let_name_here);
println!("Your input: {}", let_name_here);

输出以下内容:

Your input: 15

Your input: 15

为什么在 println! marco中有多余的 \ n .根据我的编码经验,我会假设以下内容:

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);

我不明白为什么 println! marco输出两次 \ n .如果我想在第一行的末尾使用 \ n ,并且使用这两个marcos,那将是不可能的.我错过了重要的东西吗?

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?

推荐答案

从stdin读取的字符串的末尾似乎有一个换行符.然后,println宏将换行符添加到末尾,从而产生两个换行符.

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.

您应该从从stdin读取的文本的末尾去除换行符,或者如果不想这样做,只需使用print.

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.

这篇关于生锈的println!问题-println宏内的行为异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆