【问题标题】:print! macro not executed until pressing Enter打印!宏在按 Enter 之前不会执行
【发布时间】:2021-12-19 23:42:48
【问题描述】:

我正在研究 Rust,并在处理 Guessing Game 时发现了这种奇怪的行为:

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!");
}

会发生以下情况:

  1. Welcome! 已打印
  2. Please type something: 未打印
  3. 如果您输入一些文本并按 Enter,您将看到您的文本后跟 Please type something:Bye!

如何将消息打印到标准输出并将输入打印在同一行?

例如:

Please enter your name:
(user types Chuck Norris)
Please enter your name: Chuck Norris

【问题讨论】:

  • 可能与not flushing the output buffer相关?
  • @tadman 确实我可以 `print!("Something\n") 但随后 \n 被打印了。
  • 查看我链接的相关问题。

标签: rust


【解决方案1】:

来自std::print 的文档:

请注意,默认情况下 stdout 经常是行缓冲的,因此可能需要使用 io::stdout().flush() 来确保立即发出输出。

看来您需要致电io::stdout().flush()

【讨论】:

  • 谢谢你的作品!延迟 10 分钟后,我会尽快接受您的答复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-16
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
相关资源
最近更新 更多