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

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

问题描述

我尝试编写一些代码,从标准输入读取名称并打印出来.问题是打印变量后立即换行,变量后面的字符打印在下一行:

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.

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

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