This is a simple crate that allows for easy parsing of whitespace delimited files.
It is primarily intended for competitive programming, where such files are commonly used as inputs due to being easy to parse in C and C++. This crate aims to bring this ease to Rust.
For complete programs, see the examples in the source repository.
A TokenReader
can be constructed from any type implementing BufRead
, such as a file, standard input or a byte slice.
The easiest way to handle errors is to use anyhow.
```rust use std::io::stdin;
use anyhow::Result; use token_read::TokenReader;
fn main() -> Result<()> { let mut input = TokenReader::new(stdin().lock());
// Do IO and computation
Ok(())
} ```
A tuple of one or more values of any type implementing FromStr
can be read using the line
function.
rust
let (budget, ): (u64, ) = input.line()?;
let (product, cost): (String, u64) = input.line()?;
10000
Sandwich 80
In order to read a line without any modifications, you can use the line_raw
function.
rust
let sentence: String = input.line_raw()?;
All human beings are born free and equal in dignity and rights.
The line
function can also be used to read a variable amount values of a type implementing FromStr
into most standard collections.
rust
let temperatures: Vec<f64> = input.line()?;
let allowed_letters: HashSet<char> = input.line()?;
18.7 19.2 19.4 18.9
A B E I J M N
The take
function can be used to create an iterator consuming a specific number of lines. You can use it to make a simple for
loop.
```rust let (city_count, ): (usize, ) = input.line()?;
for city in input.take(city_count) { let (name, population): (String, u64) = city?; } ```
Alternatively, it can be collected into any data structure.
rust
let (city_count, ): (usize, ) = input.line()?;
let cities: Vec<(String, u64)> = input.take(city_count).collect::<Result<_, _>>()?;
3
Prague 1309000
New York 8468000
Tokio 13960000
This crate is available from crates.io. To install, simply run:
sh
cargo add token-read