2.計算字元數

劉祺發表於2017-07-03

我的實現

一個滿足題意的實現

use std::io::{self, Write};
fn main() {
    print!("What is the input string?");
    io::stdout().flush().unwrap();
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect(
        "Failed to read line",
    );
    println!("{} has {} characters.", input, input.len());
}

學到了什麼

您可以通過增加一個迴圈來保證使用者的確輸入了內容。

use std::io::{self, Write};
fn main() {
    print!("What is the input string?");
    io::stdout().flush().unwrap();
    let mut input = String::new();
    std::io::stdin().read_line(&mut input).expect(
        "Failed to read line",
    );
    while input.len() == 0 {
        std::io::stdin().read_line(&mut input).expect(
            "Failed to read line",
        );
    }
    println!("{} has {} characters.", input, input.len());
}

當然這也不完全是一個好的實踐。

use std::io::{self, Write};
fn main() {
    print!("What is the input string?");
    io::stdout().flush().unwrap();
    let mut input = String::new();
    loop {
        std::io::stdin().read_line(&mut input).expect(
            "Failed to read line",
        );
        if input.len() != 0 {
            break;
        }
        println!("Please enter the content.");
    }
    println!("{} has {} characters.", input, input.len());
}

這裡使用了 loop 迴圈達到了一種好的實踐,因為到現在為止 Rust 中還沒有像 C 語言中那樣的 do 迴圈。後面的兩個程式都不能在 play 裡面得到滿意的結果。因為 play 裡面不能輸入。所以會導致死迴圈。

相關文章