- Rust Standard Library Cookbook
- Jan Nils Ferner Daniel Durante
- 290字
- 2021-08-27 19:45:07
How to do it...
In the src/bin folder, create a file called stdin.rs
Add the following code and run it with cargo run --bin stdin:
1 use std::io;
2 use std::io::prelude::*;
3
4 fn main() {
5 print_single_line("Please enter your forename: ");
6 let forename = read_line_iter();
7
8 print_single_line("Please enter your surname: ");
9 let surname = read_line_buffer();
10
11 print_single_line("Please enter your age: ");
12 let age = read_number();
13
14 println!(
15 "Hello, {} year old human named {} {}!",
16 age, forename, surname
17 );
18 }
19
20 fn print_single_line(text: &str) {
21 // We can print lines without adding a newline
22 print!("{}", text);
23 // However, we need to flush stdout afterwards
24 // in order to guarantee that the data actually displays
25 io::stdout().flush().expect("Failed to flush stdout");
26 }
27
28 fn read_line_iter() -> String {
29 let stdin = io::stdin();
30 // Read one line of input iterator-style
31 let input = stdin.lock().lines().next();
32 input
33 .expect("No lines in buffer")
34 .expect("Failed to read line")
35 .trim()
36 .to_string()
37 }
38
39 fn read_line_buffer() -> String {
40 // Read one line of input buffer-style
41 let mut input = String::new();
42 io::stdin()
43 .read_line(&mut input)
44 .expect("Failed to read line");
45 input.trim().to_string()
46 }
47
48 fn read_number() -> i32 {
49 let stdin = io::stdin();
50 loop {
51 // Iterate over all lines that will be inputted
52 for line in stdin.lock().lines() {
53 let input = line.expect("Failed to read line");
54 // Try to convert a string into a number
55 match input.trim().parse::<i32>() {
56 Ok(num) => return num,
57 Err(e) => println!("Failed to read number: {}", e),
58 }
59 }
60 }
61 }
推薦閱讀
- 元器件易學(xué)通:常用器件分冊
- 用萬用表檢修液晶電視機(jī)一學(xué)就會(huì)
- 圖表細(xì)說電子工程師速成手冊(第2版)
- 路由與交換技術(shù)
- 教你檢修液晶顯示器
- Android板級(jí)支持與硬件相關(guān)子系統(tǒng)
- 數(shù)字電路與系統(tǒng)
- 機(jī)載激光雷達(dá)基礎(chǔ)原理與應(yīng)用
- 太陽能光伏組件生產(chǎn)制造工程技術(shù)
- 5G移動(dòng)通信:無線網(wǎng)絡(luò)優(yōu)化技術(shù)與實(shí)踐
- 視頻精講:PADS 2007原理圖與布板設(shè)計(jì)典型實(shí)例
- 手機(jī)軟件平臺(tái)架構(gòu)解析
- 智能光網(wǎng)絡(luò)運(yùn)行維護(hù)管理
- 移動(dòng)通信技術(shù)及應(yīng)用
- TD-LTE網(wǎng)絡(luò)規(guī)劃原理與應(yīng)用