How do I print output without a trailing newline in Rust?

陌路散爱 提交于 2019-11-27 23:33:53
sjagr

You can use the print! macro instead.

print!("Enter the number : ");
io::stdin().read_line(&mut num);

Beware:

Note that stdout is frequently line-buffered by default so it may be necessary to use io::stdout().flush() to ensure the output is emitted immediately.

It's trickier than it would seem at first glance. Other answers mention the print! macro but it's not quite that simple. You'll likely need to flush stdout, as it may not be written to the screen immediately. flush() is a trait that is part of std::io::Write so that needs to be in scope for it to work (this is a pretty easy early mistake).

use std::io;
use std::io::Write; // <--- bring flush() into scope


fn main() {
    println!("I'm picking a number between 1 and 100...");

    print!("Enter a number: ");
    io::stdout().flush().unwrap();
    let mut val = String::new();

    io::stdin().read_line(&mut val)
        .expect("Error getting guess");

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