diff --git a/examples/cookbook-read-whitespace.rs b/examples/cookbook-read-whitespace.rs new file mode 100644 index 0000000..8082b97 --- /dev/null +++ b/examples/cookbook-read-whitespace.rs @@ -0,0 +1,24 @@ +use std::error::Error; +use std::io; +use std::process; + +fn example() -> Result<(), Box> { + // Build the CSV reader and iterate over each record. + let mut rdr = csv::ReaderBuilder::new() + .trim(csv::Trim::All) + .from_reader(io::stdin()); + for result in rdr.records() { + // The iterator yields Result, so we check the + // error here.. + let record = result?; + println!("{:?}", record); + } + Ok(()) +} + +fn main() { + if let Err(err) = example() { + println!("error running example: {}", err); + process::exit(1); + } +} diff --git a/examples/data/smallpop-whitespace.csv b/examples/data/smallpop-whitespace.csv new file mode 100644 index 0000000..362fc4f --- /dev/null +++ b/examples/data/smallpop-whitespace.csv @@ -0,0 +1,11 @@ +city, region, country, population +Southborough, MA, United States, 9686 +Northbridge, MA, United States, 14061 +Westborough, MA, United States, 29313 +Marlborough, MA, United States, 38334 +Springfield, MA, United States, 152227 +Springfield, MO, United States, 150443 +Springfield, NJ, United States, 14976 +Springfield, OH, United States, 64325 +Springfield, OR, United States, 56032 +Concord, NH, United States, 42605 diff --git a/src/cookbook.rs b/src/cookbook.rs index a28dc72..bc0aa58 100644 --- a/src/cookbook.rs +++ b/src/cookbook.rs @@ -14,6 +14,7 @@ For **reading** CSV: 2. [With Serde](#reading-with-serde) 3. [Setting a different delimiter](#reading-setting-a-different-delimiter) 4. [Without headers](#reading-without-headers) +5. [With whitspace](#reading-with-whitespace) For **writing** CSV: @@ -195,6 +196,46 @@ $ cd rust-csv $ cargo run --example cookbook-read-no-headers < examples/data/smallpop-no-headers.csv ``` +# Reading: with whitespace + +This example shows how to read CSV data seperated by whitespace as well as a comma. + +```no_run +# //cookbook-read-whitespace.rs +use std::error::Error; +use std::io; +use std::process; + +fn example() -> Result<(), Box> { + // Build the CSV reader and iterate over each record. + let mut rdr = csv::ReaderBuilder::new() + .trim(csv::Trim::All) + .from_reader(io::stdin()); + for result in rdr.records() { + // The iterator yields Result, so we check the + // error here.. + let record = result?; + println!("{:?}", record); + } + Ok(()) +} + +fn main() { + if let Err(err) = example() { + println!("error running example: {}", err); + process::exit(1); + } +} +``` + +The above example can be run like so: + +```ignore +$ git clone git://github.com/BurntSushi/rust-csv +$ cd rust-csv +$ cargo run --example cookbook-read-whitespace < examples/data/smallpop-whitespace.csv +``` + # Writing: basic This example shows how to write CSV data to stdout.