Why standard I/O cannot be executed in order correctly

//This is my code
fn stdio_demo() -> io::Result<()>{

    let mut s:String = String::new();

    let s_tips:String = String::from("请输入:");
    io::stdin().read_line(&mut s)?;

    s = format!("{}{}{}", "输出:", s, "\n");



I entered "test" in the terminal, but the displayed results did not execute normally

//This is the result of execution

Online waiting for guidance from the boss😂

What did yo expect and what happened instead?

In any case, there are at least 2 things wrong with your code:

  • write() isn't guaranteed to write everything; that'd be write_all(). Please read the documentation; this is clearly stated there.
  • Standard I/O is buffered by default. You won't see anything printed until a newline is encountered or you explicitly flush().

By the way, is there a reason you aren't using print!() for output? It doesn't seem like you need to call the Write impl on Stdout directly.

Thanks for your correction. The problem has been solved with flush():pray:

Never use write(). This function is an awful trap, by design. Always use write_all() instead.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.