Skip to content

Instantly share code, notes, and snippets.

@wayhoww
Created July 18, 2020 16:28
Show Gist options
  • Save wayhoww/79d4d04c0dbc5040c54c13981b421786 to your computer and use it in GitHub Desktop.
Save wayhoww/79d4d04c0dbc5040c54c13981b421786 to your computer and use it in GitHub Desktop.
simple code for reading integers and floats from stdin in Rust, for OI/ICPC/Codeforces players
/*
How to use it:
let stdin = std::io::stdin();
let (a, b): (i32, f64) = stdin.tuple_2();
let v: Vec<i32> = stdin.line();
let v: std::collections::BTreeSet<i32> = stdin.line();
let s: i32 = stdin.scalar();
let s: f64 = stdin.scalar();
Note:
All of the 3 functions read a whole line per call.
If you call stdin.scalar() while the input line is "12 13 14",
"13 14" will be abandoned forever.
*/
trait SimpleIO {
fn scalar<T>(&self) -> T
where T: core::str::FromStr;
fn tuple_2<T1, T2>(&self) -> (T1, T2)
where T1: core::str::FromStr,
T2: core::str::FromStr;
fn line<T, B>(&self) -> B
where T: core::str::FromStr,
B: core::iter::FromIterator<T>;
}
impl SimpleIO for std::io::Stdin {
// could be optimized
// ( https://stackoverflow.com/questions/38863781/how-to-create-a-tuple-from-a-vector )
fn tuple_2<T1, T2>(&self) -> (T1, T2)
where T1: core::str::FromStr,
T2: core::str::FromStr{
let mut number = String::new();
self.read_line(&mut number).unwrap();
let pieces: Vec<&str> = number.trim()
.split(' ')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.collect();
(pieces[0].parse().ok().unwrap(), pieces[1].parse().ok().unwrap())
}
fn scalar<T>(&self) -> T
where T: core::str::FromStr{
let mut number = String::new();
self.read_line(&mut number).unwrap();
number.trim().parse().ok().unwrap()
}
fn line<T, B>(&self) -> B
where T: core::str::FromStr,
B: core::iter::FromIterator<T>{
let mut number = String::new();
self.read_line(&mut number).unwrap();
number.trim()
.split(' ')
.map(|s| s.trim())
.filter(|s| !s.is_empty())
.map(|s| s.parse().ok().unwrap())
.collect()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment