官术网_书友最值得收藏!

  • Rust Standard Library Cookbook
  • Jan Nils Ferner Daniel Durante
  • 290字
  • 2021-08-27 19:45:07

How to do it...

  1. In the src/bin folder, create a file called stdin.rs

  2. 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 }
主站蜘蛛池模板: 屏东县| 榆林市| 海原县| 财经| 巧家县| 巴彦县| 黑水县| 尼勒克县| 双流县| 颍上县| 民和| 汕尾市| 汽车| 桂东县| 东源县| 五常市| 休宁县| 霍林郭勒市| 呼伦贝尔市| 富锦市| 承德市| 庆城县| 东莞市| 武冈市| 卫辉市| 延安市| 如东县| 静乐县| 米易县| 娱乐| 红桥区| 宿州市| 平邑县| 云梦县| 凌海市| 鄂尔多斯市| 安国市| 云浮市| 娱乐| 五常市| 定襄县|