我正在研究 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!");
}
Run Code Online (Sandbox Code Playgroud)
发生以下情况:
Welcome! 被打印Please type something: 不打印Please type something:Bye!如何将消息打印到标准输出并将输入打印在同一行上?
例如:
Please enter your name:
(user types Chuck Norris)
Please enter your name: Chuck Norris
Run Code Online (Sandbox Code Playgroud)
从文档中std::print:
请注意,默认情况下 stdout 经常是行缓冲的,因此可能需要使用 io::stdout().flush() 来确保立即发出输出。
所以看起来你需要调用io::stdout().flush().
| 归档时间: |
|
| 查看次数: |
96 次 |
| 最近记录: |