Sub topic 11
Reading all of standard input at once
This chapter covers read_to_string, which collects everything on standard input into one String. It assumes you can already use read_line, handle an io::Result with ?, and parse text with str::parse. It also assumes you know what BufRead and lines() do.
When to read everything first
read_line and lines() process input one line at a time. That works well when each line can be handled without looking at the others. Some tasks need the whole input before they can start:
- Computing a median, sorting, or removing duplicates.
- Making two passes, for example finding the maximum and then printing each value as a percentage of it.
- Parsing a document whose structure spans lines, such as a header followed by a body.
- Reporting an error with a location in the full text.
For these, reading everything into one String and working on it in memory is simpler than building up state line by line.
The basic call
read_to_string belongs to the Read trait. You must import the trait, or the method will not be found.
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(())
}Four details matter here.
- It appends. The method does not clear the buffer. If
inputalready held text, the new data goes after it. - It returns the number of bytes added. The value is
Ok(n), and you can ignore it if you only need the string. - It blocks until end of input. The call returns only when stdin is closed. For a pipe or redirected file, that happens when the writer finishes.
- It requires valid UTF-8. If the bytes are not valid UTF-8, you get an
io::Errorof kindInvalidData, and the buffer is left unchanged.
Giving the program input
When stdin is a terminal, read_to_string waits until you signal end of input. Type your text, then press Ctrl-D at the start of a line on Linux and macOS. On Windows, press Ctrl-Z and then Enter. Piping and redirection are usually easier:
printf 'one two\nthree\n' | cargo run
cargo run < notes.txtThe earlier chapter on Ok(0) covered how read_line signals end of input. read_to_string has the same end-of-input condition, but it consumes everything up to that point in one call.
The free function form
Since Rust 1.65, std::io::read_to_string takes any reader and returns a new String. It saves the separate let mut line:
use std::io;
fn main() -> io::Result<()> {
let input = io::read_to_string(io::stdin())?;
println!("{} words", input.split_whitespace().count());
Ok(())
}Use the method when you want to append to an existing buffer. Use the function when you want a fresh string.
Working with the string afterward
Once the text is in memory, you can slice it, iterate over it as many times as you like, and keep references into it. The two most common starting points are lines() and split_whitespace().
str::lines splits on \n and also strips a trailing \r, so Windows line endings (CRLF) are handled for you. A final line without a newline is still returned. An empty string yields zero lines.
The next program reads whitespace-separated integers from any number of lines and prints summary statistics. The median requires sorting, which is why it needs all of the data at once.
use std::error::Error;
use std::io::{self, Read};
fn main() -> Result<(), Box<dyn Error>> {
let mut input = String::new();
io::stdin().read_to_string(&mut input)?;
let mut numbers = input
.split_whitespace()
.map(|token| token.parse::<i64>())
.collect::<Result<Vec<i64>, _>>()?;
if numbers.is_empty() {
println!("no numbers");
return Ok(());
}
numbers.sort_unstable();
let count = numbers.len();
let sum: i64 = numbers.iter().sum();
let median = if count % 2 == 1 {
numbers[count / 2] as f64
} else {
(numbers[count / 2 - 1] + numbers[count / 2]) as f64 / 2.0
};
println!("count = {count}");
println!("sum = {sum}");
println!("min = {}", numbers[0]);
println!("max = {}", numbers[count - 1]);
println!("median = {median}");
Ok(())
}Run it with six numbers:
printf '4 8 15\n16 23 42\n' | cargo runcount = 6
sum = 108
min = 4
max = 42
median = 15.5The collect::<Result<Vec<i64>, _>>() call stops at the first token that fails to parse and returns that error. The ? then converts the ParseIntError into a Box<dyn Error>. This is the same mixing of error types you saw in the Box<dyn Error> section, now applied to a whole input. If you would rather skip bad tokens and report them, as the line-by-line sum program did, write a for loop with a match instead of collect.
Empty input is a valid case
If stdin is empty, read_to_string returns Ok(0) and leaves the string empty. It is not an error. The program above handles this with the is_empty check. Without that check, numbers[0] would panic with an index out of bounds. Decide explicitly what your program does when there is nothing to read.
Comparing the three approaches
| Approach | Memory use | Starts work before input ends | Good for |
|---|---|---|---|
| `read_line` in a loop | One line at a time | Yes | Interactive prompts, simple filters |
| `stdin().lock().lines()` | One line at a time | Yes | Streaming through large or endless input |
| `read_to_string` | The whole input | No | Sorting, multiple passes, whole-document parsing |
The last row has two consequences.
- Memory grows with input size. Piping a 4 GB file into a program that calls
read_to_stringallocates roughly 4 GB, and possibly more while theStringgrows by reallocation. For data you only need to scan once, preferlines(). - It cannot be used interactively. A program that waits for end of input before doing anything will appear to hang when a user types at the terminal. An interactive prompt loop needs
read_line.
Input that is not valid UTF-8
A String must hold valid UTF-8. Files in legacy encodings, or binary data, will make read_to_string fail with InvalidData. If you want to accept such input anyway, read raw bytes with read_to_end and decide how to convert them:
use std::io::{self, Read};
fn main() -> io::Result<()> {
let mut bytes = Vec::new();
io::stdin().read_to_end(&mut bytes)?;
let text = String::from_utf8_lossy(&bytes);
println!("{} bytes, {} lines", bytes.len(), text.lines().count());
Ok(())
}String::from_utf8_lossy replaces each invalid sequence with the character U+FFFD, so you never get an error. The result is a Cow<str>. It borrows from bytes when the data was already valid and allocates only when it had to replace something. Use String::from_utf8(bytes) instead if you want a hard error on bad input and want to keep the original bytes when it fails.
Byte order marks
Some Windows tools write a UTF-8 byte order mark (U+FEFF) at the start of a file. read_to_string keeps it as part of the first token, so parsing the first number can fail even though the file looks fine. If you expect such files, remove it with input.strip_prefix('\u{feff}').
Mixing with other readers
Standard input has one buffer that is shared by the whole process, and io::stdin() hands out handles to it. Because of that, you can read a header with read_line and then collect the rest with read_to_string:
use std::io::{self, Read};
fn main() -> io::Result<()> {
let mut header = String::new();
io::stdin().read_line(&mut header)?;
let mut body = String::new();
io::stdin().read_to_string(&mut body)?;
println!("header: {:?}", header.trim());
println!("body has {} lines", body.lines().count());
Ok(())
}The second call continues where the first stopped, with nothing lost or read twice. Keep the order in mind: once read_to_string has run, stdin is at end of input, and later reads return Ok(0).
Making it testable
The earlier chapters showed that a function taking impl BufRead can be tested with in-memory data. The same idea applies here, with Read as the bound. Keep the reading in main and put the logic in a function that takes &str, which is even easier to test:
use std::io;
fn count_words(text: &str) -> usize {
text.split_whitespace().count()
}
fn main() -> io::Result<()> {
let input = io::read_to_string(io::stdin())?;
println!("{}", count_words(&input));
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn counts_across_lines() {
assert_eq!(count_words("a b\nc d\n"), 4);
}
#[test]
fn empty_text_has_no_words() {
assert_eq!(count_words(""), 0);
}
}Separating "get the text" from "interpret the text" is the main benefit of reading all input first. The interpretation step is a pure function of a string.
Common mistakes
- Forgetting
use std::io::Read. The compiler reports that no methodread_to_stringexists onStdin, and it suggests importing the trait. - Reusing a dirty buffer. Because the method appends, a
Stringreused inside a loop accumulates old data unless you callclear()first. - Expecting a prompt to work. A program that prints a prompt and then calls
read_to_stringleaves the user typing with no sign of when to stop. Tell them about Ctrl-D, or read a single line instead. - Indexing without checking for empty input. Empty stdin is not an error, so
v[0]on an empty vector panics. - Using it on unbounded input. If the size is not known, use
lines()and process as you go.
Exercise
A program calls io::stdin().read_to_string(&mut buf) where buf already contains "abc". Stdin supplies "xyz\n" and then ends. What does buf contain afterward, and what does the call return?
Show answer
buf contains "abcxyz\n", because read_to_string appends to the existing contents. The call returns Ok(4), the number of bytes added ("xyz" plus the newline).
Exercise
Write a function fn longest_line(text: &str) -> Option<&str> and say why it is easier to test than a version that reads stdin itself. Then name the one change that makes main read the text from stdin.
Show answer
One solution is fn longest_line(text: &str) -> Option<&str> { text.lines().max_by_key(|l| l.len()) }. It returns None for empty text. It is easy to test because a test can pass a string literal such as "a\nbbb\ncc" and check for Some("bbb"), with no terminal or pipe needed. In main, call let input = io::read_to_string(io::stdin())?; (or use read_to_string with a String buffer and use std::io::Read) and pass &input to the function.