How to avoid going to new line with stdin in Rust

我的梦境 提交于 2019-12-08 01:04:24

问题


I have this code:

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

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

So when I input something, the programs returns "Your age:" plus my input. But when I run the program I don't want to write the input in a new line. To do something like that in Python, I can write:

var = input("Your age: ")

How can I avoid going to a new line? I'm sure it's simple but I really can't realize how to do that, I tried a lot of different stuff...


回答1:


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.



来源:https://stackoverflow.com/questions/39154107/how-to-avoid-going-to-new-line-with-stdin-in-rust

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