我试图在同一行上打印,因为我希望输入问题是内联的,例如“输入某些内容:输入在此处”。与python的类似input("input: ")。如果我尝试这样做,print!文本不会显示,而是在我按回车键后显示。我尝试过刷新缓冲区。
print!("enter some thing: ");
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
println!("{}", input);
Run Code Online (Sandbox Code Playgroud)
上面的代码输出将是:
hello
enter some thing: hello
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况?
将print!要打印的文本添加到缓冲区,但不会刷新该缓冲区以立即将其输出到终端,以在打印大量内容时提高性能。
您说您尝试刷新缓冲区(如本问题中所建议的),但也许您没有在正确的位置刷新它?您需要在读取之前刷新它stdin。这对我有用:
use std::io::Write;
print!("enter some thing: ");
std::io::stdout().flush().unwrap();
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
print!("{}", input);
Run Code Online (Sandbox Code Playgroud)
运行示例:
use std::io::Write;
print!("enter some thing: ");
std::io::stdout().flush().unwrap();
let mut input = String::new();
std::io::stdin().read_line(&mut input).expect("Failed to read line");
print!("{}", input);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3570 次 |
| 最近记录: |