How to avoid going to new line with stdin in Rust

巧了我就是萌 提交于 2019-12-06 06:34:38
antoyo

You need to flush stdout before reading the line:

use std::io::{self, Write};

fn main() {
    let mut stdin = io::stdin();
    let input = &mut String::new();

    loop {
        input.clear();
        print!("Your age: ");
        io::stdout().flush();
        stdin.read_line(input);
        print!("{}", input);
    }
}

From the print! documentation:

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.

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