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::stdout().write(s_tips.as_bytes())?;
    io::stdin().read_line(&mut s)?;

    //标准输出
    s = format!("{}{}{}", "输出:", s, "\n");
    io::stdout().write(s.as_bytes())?;

    Ok(())

}

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

//This is the result of execution
test
请输入:输出:test
![image|599x284](upload://63IFjCNJIxZhA7SH4bZ6acQaQW8.png)

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.