Sub topic 11
Reading All of Standard Input at Once
This chapter assumes you can read a line with read_line, handle an io::Result with ?, and iterate over lines() on a locked stdin. Here you will read everything until end of input in a single call.
Why read everything at once
read_line and lines() process input piece by piece. That suits interactive prompts and streams. Sometimes you need the whole input before you can act on it. You might want to count lines, parse a block of data in several passes, or hand the full text to a function that takes a &str.
The Read trait provides read_to_string for this. It appends all remaining bytes to a String and stops at end of input.
The basic program
use std::io::{self, Read};
fn main() -> io::Result<()> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
println!("{} bytes, {} lines", input.len(), input.lines().count());
Ok(())
}Three details matter here.
read_to_stringcomes from theReadtrait. Withoutuse std::io::Read, the method is not in scope and the compiler reports that it cannot find it.- It returns
io::Result<usize>, the number of bytes appended. The example ignores the number and uses?for the error. input.len()counts bytes, not characters. For text with non-ASCII characters, the byte count is larger than the character count.
str::lines() splits the text at \n and also removes a trailing \r, so it handles both Unix and Windows line endings. A final newline does not produce an extra empty line.
How it behaves when run
Run the program with piped input:
printf 'alpha\nbeta\ngamma\n' | cargo runIt prints 17 bytes, 3 lines. When you run it with no pipe, it waits for you to type. Nothing is processed until you signal end of input with Ctrl-D on Linux and macOS, or Ctrl-Z followed by Enter on Windows.
Choosing between the approaches
| Approach | Memory use | Starts work | Best for |
|---|---|---|---|
| `read_line` | One line | After each line | Interactive prompts |
| `lines()` on locked stdin | One line at a time | After each line | Streaming, large input |
| `read_to_string` | Whole input | After end of input | Multi-pass or whole-text work |
Common errors
- Invalid UTF-8.
read_to_stringrequires valid UTF-8. If the input contains other bytes, it returns anErrwith kindInvalidData. If you need raw bytes, useread_to_endwith aVec<u8>. - Mixing readers.
io::stdin()shares one internal buffer. If you callread_linefirst andread_to_stringafterwards, the second call gets only what remains, which is not an error but can surprise you. - Forgetting end of input. In a terminal, the program seems to hang until you press Ctrl-D. This is normal behavior.
- Assuming a trailing newline. If you split by
'\n'yourself, a final newline gives an empty last item.lines()avoids this.
Parsing the whole text
Once you have the String, you can treat it like any other text. This example reads all integers, however they are spread across lines, and reports the largest:
use std::io::{self, Read};
fn main() -> io::Result<()> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
let numbers: Vec<i64> = input
.split_whitespace()
.filter_map(|token| token.parse().ok())
.collect();
match numbers.iter().max() {
Some(max) => println!("{} numbers, largest is {max}", numbers.len()),
None => println!("no numbers found"),
}
Ok(())
}filter_map with .ok() silently drops tokens that fail to parse. That is convenient but hides bad data. If you need to report errors, use a match on each token, as in the earlier chapter on tokens.
Exercise
Why does a program that calls readtostring appear to hang when you run it in a terminal without piping anything in, and how do you end it on Linux?
Show answer
readtostring keeps reading until it sees end of input, and a terminal only reports end of input when you send it. Press Ctrl-D (on a line by itself or after typing text) so the call returns and the program continues.
Exercise
Change the second program so it prints an error message to stderr for any token that is not a valid i64, while still computing the largest valid number. Which method would you replace filter_map with?
Show answer
Replace the filtermap closure with a for loop over input.splitwhitespace(). In it, match token.parse::<i64>(): push the number onto the vector on Ok, and call eprintln!("skipping {token:?}") on Err.