锈:打印!宏直到按Enter才执行
我正在研究 Rust,在做猜谜游戏时,我发现了这种奇怪的行为:
use std::io;
fn main() {
println!("Welcome!");
let mut input = String::new();
print!("Please type something:"); // this line is not printed UNTIL the Enter key is pressed
io::stdin()
.read_line(&mut input)
.expect("Failed to read input!");
println!("Bye!");
}
发生以下情况:
Welcome!被打印Please type something:不打印- 如果您输入一些文本并按 Enter,您将看到您的文本后跟
Please type something:Bye!
如何将消息打印到标准输出并将输入打印在同一行上?
例如:
Please enter your name:
(user types Chuck Norris)
Please enter your name: Chuck Norris
回答
从文档中std::print:
请注意,默认情况下 stdout 经常是行缓冲的,因此可能需要使用 io::stdout().flush() 来确保立即发出输出。
所以看起来你需要调用io::stdout().flush().