打印从stdin读取的字符串时,如何忽略换行符? [英] How to ignore the line break while printing a string read from stdin?

查看:175
本文介绍了打印从stdin读取的字符串时,如何忽略换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一些代码,该代码从stdin读取名称并打印出来.问题是在打印变量后,该行立即中断,并且该变量之后的字符在下一行中打印:

I tried to write a bit of code which reads a name from stdin and prints it. The problem is the line breaks immediately after printing the variable and the characters following the variable are printed in the next line:

use std::io;

fn main() {
    println!("Enter your name:");
    let mut name = String::new();
    io::stdin().read_line(&mut name).expect("Failed To read Input");
    println!("Hello '{}'!", name);
}

'!'在下一行而不是预期位置打印.

The '!' is printed in the next line, which is not the expected location.

推荐答案

使用 .trim() 删除字符串上的空格.这个例子应该可以.

Use .trim() to remove whitespace on a string. This example should work.

use std::io;

fn main() {
    println!("Enter your name:");
    let mut name = String::new();
    io::stdin().read_line(&mut name).expect("Failed To read Input");
    println!("Hello '{}'!", name.trim());
}

还有 trim_start() .trim_end() 只能从字符串的一侧删除空格更改.

There also trim_start() and .trim_end() if you need to remove whitespace changes from only one side of the string.

这篇关于打印从stdin读取的字符串时,如何忽略换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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