Existing answers I\'ve found are all based on from_str
(such as Reading in user input from console once efficiently), but apparently from_str(x)
h
If you are looking for a way to read input for the purpose of competitive programming in websites like codechef or codeforces where you do not have access to text_io
.
This is not a new way to read rather one mentioned in the above answers, I just modified it to suit my needs.
I use the following macro to read from stdin the different values:
use std::io;
#[allow(unused_macros)]
macro_rules! read {
($out:ident as $type:ty) => {
let mut inner = String::new();
io::stdin().read_line(&mut inner).expect("A String");
let $out = inner.trim().parse::<$type>().expect("Parseble");
};
}
#[allow(unused_macros)]
macro_rules! read_str {
($out:ident) => {
let mut inner = String::new();
io::stdin().read_line(&mut inner).expect("A String");
let $out = inner.trim();
};
}
#[allow(unused_macros)]
macro_rules! read_vec {
($out:ident as $type:ty) => {
let mut inner = String::new();
io::stdin().read_line(&mut inner).unwrap();
let $out = inner
.trim()
.split_whitespace()
.map(|s| s.parse::<$type>().unwrap())
.collect::>();
};
}
In main
fn main(){
read!(x as u32);
read!(y as f64);
read!(z as char);
println!("{} {} {}", x, y, z);
read_vec!(v as u32); // Reads space separated integers and stops when newline is encountered.
println!("{:?}", v);
}
NOTE: I am no Rust Expert, if you think there is a way to improve it, please let me know. It will help me, Thanks.