2014-09-02 55 views
1

我最近學會了如何使用io從防火牆文檔讀取輸入,但我想知道是否有任何'簡單'方法讀取控制檯輸入。我的根源深深植入C++,所以從控制檯獲取輸入就像std::cin >> var一樣簡單。但鏽我做:一次從控制檯讀取用戶輸入一次

for line in io::stdin().lines() { 
    print!("{}", line.unwrap()); 
    break; 
} 

這種讀取輸入一次,但for循環看起來像一個非常笨拙的方式來做到這一點。我怎樣才能輕鬆做到這一點?

回答

4

io::stdin()實際上是一個BufferedReader<>包裝stdin。如您所見,in the docsBufferedReader提供了很多提取內容的方法。

你必須值得注意的是:

fn read_line(&mut self) -> IoResult<String> 

將嘗試讀取從標準輸入線(也可能返回一個錯誤)。一個簡單的代碼來讀取int從標準輸入將是:

let a: int = from_str(io::stdin().read_line().unwrap().as_slice()).unwrap() 

但它沒有任何錯誤處理,並可以很容易失敗。

更明確的辦法將要求您更清潔處理事情:

let a: int = match from_str(
    match io::stdin().read_line() { 
     Ok(txt) => txt, // Return the slice from_str(...) expects 
     Err(e) => { /* there was an I/O Error, details are in e */ } 
    }.as_slice()) /* match from_str(...) */ { 
     Some(i) => i, // return the int to be stored in a 
     None => { /* user input could not be parsed as an int */ } 
    }; 
+0

Rust告訴我'txt'不夠長,無法在第二次執行的下一個塊中匹配,我怎麼能通過? – 2014-09-03 20:18:19

+0

沒關係固定,as_slice()必須移動到第一個匹配語句的末尾 – 2014-09-03 20:28:10

+0

@SyntacticFructose哦,是的,的確,好抓!我會糾正它。 – Levans 2014-09-03 20:46:08

4

std::io::stdin()返回BufferedReader<StdReader>BufferedReader實現Buffer性狀。這意味着,你可以調用它read_line()方法:

match io::stdin().read_line() { 
    Ok(line) => // do whatever you want, line is String 
    Err(e) => // handle error, e is IoError 
} 

如果你想讀幾行,它可能是更好的io::stdin()結果保存到一個變量第一。

+0

目前,在* read_line *功能需要一個參數,一個可變引用到*字符串*。欲瞭解更多信息,請點擊[這裏](https://doc.rust-lang.org/std/io/struct.Stdin.html#method.read_line)。 – freinn 2017-02-27 19:17:33

相關問題