better_input/
lib.rs

1use std::io::{stdin,stdout,Write};
2
3
4/// Reads a line from stdin() and returns up to max characters in a String.
5/// 
6/// This function will always remove trailing \n and the \r on Windows only.
7/// 
8/// It also does not break if a EOF is reached and instead acts as if a newline was reached prints one itself.
9pub fn readline<T>(max: usize, query: T) -> String where T: std::fmt::Display{
10    let mut out: String = String::new();
11    print!("{}", query);
12    let _ = stdout().flush();
13    match stdin().read_line(&mut out){
14        Ok(n) => {
15            if n >= max{
16                if !out.ends_with('\n') {println!();}
17                out.truncate(max);
18                return out
19            }
20            else{
21                if out.ends_with('\n') {
22                    out.pop();
23                }
24                else {println!();}
25                if cfg!(windows) && out.ends_with('\r') {
26                    out.pop();
27                }
28                return out
29            }
30        }
31        Err(error) => {println!("We got an error while getting input \nThe error is: {}", error); return out}
32    };
33}
34
35
36/// Reads lines from stdin() until the maximum of characters is met.
37/// Do keep in mind that \n's and on Windows \r's too also count towards the charcter count.
38/// 
39/// This function will always remove trailing \n and the \r on Windows only.
40/// 
41/// It also does not break if a EOF is reached and instead acts as if a newline was reached prints one itself.
42pub fn readlines<T>(max: usize, query: T) -> String where T: std::fmt::Display{
43    let mut out: String = String::new();
44    print!("{}", query);
45    let _ = stdout().flush();
46    let mut charcters: usize = 0;
47    loop{
48        match stdin().read_line(&mut out){
49            Ok(n) => {charcters += n;
50                if charcters >= max{
51                if !out.ends_with('\n') {println!();}
52                out.truncate(max);
53                return out
54                }
55                else if charcters == max + 1 {
56                    if out.ends_with('\n') {
57                        out.pop();
58                    }
59                    else {println!();}
60                    if cfg!(windows) && out.ends_with('\r') {
61                        out.pop();
62                    }
63                    return out
64                }
65            }
66            Err(error) => {println!("We got an error while getting input \nThe error is: {}", error);}
67        };
68    }
69}