1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
mod tests;
use std::any::TypeId;
use std::io::stdin;
use std::io::BufRead;
use std::str::FromStr;
pub fn read_stdin<T>() -> Result<T, <T as FromStr>::Err>
where
T: FromStr + 'static,
{
let mut stdin = stdin().lock();
let mut buf: String = String::new();
while stdin.read_line(&mut buf).is_err() {
println!("Failed to read line. Please try again.");
}
if TypeId::of::<T>() != TypeId::of::<String>() {
buf = buf.trim().to_string();
}
buf.parse::<T>()
}
pub fn read_stdin_until_ok<T>() -> T
where
T: FromStr + 'static,
{
loop {
match read_stdin::<T>() {
Ok(value) => return value,
Err(_) => {
println!("Failed to parse. Please input a correct data type.");
continue;
}
}
}
}