-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuser_input.rs
More file actions
53 lines (37 loc) · 1.32 KB
/
user_input.rs
File metadata and controls
53 lines (37 loc) · 1.32 KB
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
#![allow(dead_code)]
use std::io::{self, Write};
/* ----------------------------------
* ------- EXECUTE -------
* ----------------------------------
*/
pub fn run() {
basics();
cast_input_as_u8();
}
// ##########################
// ### USER INPUT ###
// ##########################
fn basics() {
print!("Enter a string: ");
io::stdout().flush() // flush() in std::io::Write
.expect("Manual flush failed."); // Flush required to get entered input on same line as prompt text
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("The characters should be reprinted as is.");
println!("You entered: {}", guess.trim_end()) // Trim trailing newline
}
fn cast_input_as_u8() {
let number: u8;
loop {
println!("Enter a 8-bit number below: ");
let mut buffer = String::new();
io::stdin().read_line(&mut buffer)
.expect("No characters should be able to crash the program.");
number = match buffer.trim_end().parse() {
Ok(num) => num,
Err(_) => continue
};
break; // Only reached after successful parse
}
print!("You entered: {}", number);
}