Sub topic 6
Showing a prompt and flushing stdout
This chapter explains why a prompt printed with print! can fail to appear before your program waits for input. It then shows how to fix that with flush. It assumes you can already read a line with read_line and handle its io::Result, as covered in the earlier chapters. It also assumes you know what a trait is well enough to import one with use.
The problem: a prompt that shows up late
A prompt is text that tells the user what to type, such as Enter your age: . Most prompts stay on the same line as the cursor, so they use print! instead of println!. Here is a first attempt:
use std::io;
fn main() {
print!("Enter your name: ");
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("failed to read line");
println!("Hello, {}!", input.trim());
}This compiles without warnings. When you run it in a terminal, the cursor often sits on a blank line with no prompt. You type a name and press Enter. Only then do the prompt and the greeting appear together:
Alice
Enter your name: Hello, Alice!The program did print the prompt, but the text was not delivered to the terminal until later. To see why, you need to know how Rust buffers output.
Why the prompt is delayed
Writing to a terminal or file is a system call, and system calls are slow compared with copying bytes in memory. To avoid making one system call per print!, Rust's standard output keeps an in-memory buffer. A buffer is a block of memory that collects bytes until it is time to send them on.
Rust's Stdout is line-buffered. This means it holds your text until one of these happens:
- A newline (
\n) is written. Everything up to and including the newline is sent. - The buffer fills up.
- You call
flush, which sends everything in the buffer right away. - The program exits normally, for example when
mainreturns.
println! ends with a newline, so it triggers a send. print!("Enter your name: ") has no newline, so the text stays in the buffer. Then read_line blocks, which means the program stops and waits for you. Nothing flushes the buffer while it waits. The prompt is only sent after you press Enter and main finishes.
Rust does not flush stdout for you when you read from stdin. Some other languages and C libraries do, which is why a missing flush can surprise people who have used them. In Rust you have to do it yourself.
Flushing explicitly
The flush method belongs to the std::io::Write trait. The trait must be in scope to call the method, so you import it. Stdout implements Write, and flush returns an io::Result<()>:
use std::io::{self, Write};
fn main() -> io::Result<()> {
print!("Enter your age: ");
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
match input.trim().parse::<u32>() {
Ok(age) => println!("Next year you will be {}.", age + 1),
Err(e) => println!("Not a valid number: {e}"),
}
Ok(())
}Three details are worth noting:
use std::io::{self, Write};brings in both theiomodule name and theWritetrait. If you leave outWrite, the compiler reports that no method namedflushis found forStdout, and it suggests importing the trait.io::stdout()returns a handle to the one shared standard output. Calling it repeatedly is cheap and always refers to the same buffer, so flushing a fresh handle flushes the same data you wrote withprint!.mainnow returnsio::Result<()>, so?can pass errors up. This is the same pattern you used forread_lineearlier.
Why flush returns a Result
Flushing performs the actual write, so this is where a failure shows up. For example, the output might be a closed pipe (yourprogram | head -n 0) or a full disk. With print!, such a failure causes a panic. With flush, you get an Err that you can handle.
You have three reasonable options:
| Style | Meaning | When to use it |
|---|---|---|
| `io::stdout().flush()?;` | Return the error from the current function | Functions that already return `io::Result` |
| `io::stdout().flush().expect("flush failed");` | Panic with a message on error | Short scripts and examples |
| `let _ = io::stdout().flush();` | Ignore the error on purpose | Prompts where a broken output should not stop the program |
Leaving off the ? and writing only io::stdout().flush(); compiles, but the compiler warns about an unused Result. Treat that warning as a sign that you skipped a decision.
A reusable prompt function
Calling print!, flush, and read_line together in every place you ask a question gets repetitive. A small helper keeps the three steps in one place:
use std::io::{self, Write};
fn prompt(message: &str) -> io::Result<String> {
print!("{message}");
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Ok(input.trim().to_string())
}
fn main() -> io::Result<()> {
let name = prompt("Name: ")?;
let city = prompt("City: ")?;
println!("{name} lives in {city}.");
Ok(())
}The helper returns an owned String instead of a reference into a local buffer. Returning a reference would fail to compile, because input is dropped when the function ends. Calling .trim().to_string() copies the trimmed text into a new String that the caller owns.
This version has one limit. If input has ended (the user pressed Ctrl-D, or a pipe ran out), read_line returns Ok(0) and the helper returns an empty string. It cannot tell "the user typed nothing" from "there is no more input." The next chapter shows how to detect that case.
Alternatives to flushing stdout
Lock stdout once
Each print! call locks stdout, writes, and unlocks. If you print several prompt fragments in a row, you can take the lock once and write through it:
use std::io::{self, Write};
fn main() -> io::Result<()> {
let stdout = io::stdout();
let mut out = stdout.lock();
write!(out, "Width: ")?;
out.flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
writeln!(out, "You entered {}", input.trim())?;
Ok(())
}write! and writeln! work like print! and println!, but they write to any value that implements Write and return an io::Result. This form is useful when you want errors returned instead of panics. For a plain prompt it adds ceremony, so most programs keep using print! plus flush.
Print the prompt to stderr
Standard error (stderr) is the second output stream, meant for diagnostics. Rust's Stderr is not buffered, so eprint! appears immediately and needs no flush:
use std::io;
fn main() -> io::Result<()> {
eprint!("Enter a number: ");
let mut input = String::new();
io::stdin().read_line(&mut input)?;
match input.trim().parse::<f64>() {
Ok(n) => println!("{}", n * 2.0),
Err(e) => eprintln!("Not a number: {e}"),
}
Ok(())
}This also changes where the prompt goes when output is redirected. If a user runs cargo run > result.txt, the prompt still shows in the terminal and result.txt contains only the answer. With print!, the prompt text would be written into the file. Programs whose output is meant to be piped into other tools often send prompts to stderr for this reason.
The cost is that people do not expect prompts on stderr, and some tools capture stderr separately. For a program that is only used interactively, print! with flush is the more common choice.
Common mistakes
- Forgetting
use std::io::Write. The error message mentions a missing methodflush. Add the import. - Flushing after
read_lineinstead of before. The flush must happen before the call that blocks. Flushing afterward just reproduces the late-prompt problem. - Using
print!for the prompt and thenprintln!for the next prompt. A newline later in the output flushes everything before it, so a missing flush can go unnoticed in a program with many prompts. The bug only shows on the last prompt before a read. - Testing only with piped input. When you run
echo 25 | cargo run, no human is waiting, so a late prompt does not look wrong. Test prompts in an interactive terminal. - Expecting
flushto clear the input.flushon stdout only sends output. It has no effect on stdin or on text the user has already typed.
Summary of the output calls
| Call | Stream | Buffered | Needs flush for a prompt |
|---|---|---|---|
| `print!` | stdout | Yes, line-buffered | Yes |
| `println!` | stdout | Yes, line-buffered | No, the newline sends it |
| `eprint!` | stderr | No | No |
| `write!(out, ...)` | Any `Write` value | Depends on the writer | For stdout, yes |
Exercise
The program below prints its prompt only after the user presses Enter. Explain why, then fix it so the prompt is visible first. The fixed program must still compile and return io::Result<()> from main. use std::io; fn main() -> io::Result<()> { print!("Pick a number: "); let mut input = String::new(); io::stdin().read_line(&mut input)?; println!("You picked {}", input.trim()); Ok(()) }
Show answer
print! writes no newline, and Rust's stdout is line-buffered, so the prompt stays in the buffer while readline blocks. Nothing flushes it until a newline is written or the program ends. The fix is to import the Write trait and call flush before readline: use std::io::{self, Write}; fn main() -> io::Result<()> { print!("Pick a number: "); io::stdout().flush()?; let mut input = String::new(); io::stdin().read_line(&mut input)?; println!("You picked {}", input.trim()); Ok(()) }
Exercise
You run your prompting program as cargo run > out.txt and are surprised that the prompt text ends up inside out.txt. What small change keeps the prompt on the terminal and only the answer in the file, and why does it also remove the need for flush?
Show answer
Print the prompt with eprint! instead of print!. The redirect > out.txt only captures stdout, so a prompt written to stderr still goes to the terminal. Rust's stderr is unbuffered, so the prompt is sent immediately and no flush call is needed.