如何避免在Rust中使用stdin换行 [英] How to avoid going to new line with stdin in Rust
问题描述
我有此代码:
fn main() {
let mut stdin = io::stdin();
let input = &mut String::new();
loop {
input.clear();
print!("Your age: ");
stdin.read_line(input);
print!("{}", input);
}
}
因此,当我输入某些内容时,程序将返回您的年龄:"加上我的输入. 但是,当我运行程序时,我不想在新行中编写输入. 要在Python中执行类似的操作,我可以编写:
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...
推荐答案
在读取以下行之前,您需要先刷新stdout
:
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);
}
}
从 print!
文档:
请注意,默认情况下,stdout通常是行缓冲的,因此可能有必要使用
io::stdout().flush()
来确保立即发出输出.
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.
这篇关于如何避免在Rust中使用stdin换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!