2015-05-12 22 views

risposta

16

In How to read user input in Rust?, si può vedere come iterare su tutte le linee:

use std::io::{self, BufRead}; 

fn main() { 
    let stdin = io::stdin(); 
    for line in stdin.lock().lines() { 
     println!("{}", line.unwrap()); 
    } 
} 

È anche possibile scorrere manualmente senza un ciclo for:

use std::io::{self, BufRead}; 

fn main() { 
    let stdin = io::stdin(); 
    let mut iterator = stdin.lock().lines(); 
    let line1 = iterator.next().unwrap().unwrap(); 
    let line2 = iterator.next().unwrap().unwrap(); 
} 

Non è possibile ottenere una battuta a Fai quello che vuoi. Ma il seguente ottiene una sola linea (ed è esattamente la stessa risposta come in How do I read a single String from standard input?):

use std::io::{self, BufRead}; 

fn main() { 
    let stdin = io::stdin(); 
    let line1 = stdin.lock().lines().next().unwrap().unwrap(); 
} 

È anche possibile utilizzare il text_io cassa per super semplice ingresso:

#[macro_use] extern crate text_io; 

fn main() { 
    // reads until a \n is encountered 
    let line: String = read!("{}\n"); 
} 
+3

Che dire di [Stdin :: read_line] (http://doc.rust-lang.org/nightly/std/io/struct.Stdin.html#method.read_line)? – Gerstmann

+0

@Gerstmann: questa funzione è piuttosto strana da usare secondo me. –

5

Se vuoi veramente l'equivalente a fgets, quindi a @Gerstmann is right, dovresti usare Stdin::read_line. Questo metodo accetta un buffer che si ha un maggiore controllo del mettere la stringa in:

use std::io::{self, BufRead}; 

fn main() { 
    let mut line = String::new(); 
    let stdin = io::stdin(); 
    stdin.lock().read_line(&mut line).unwrap(); 
    println!("{}", line) 
} 

A differenza di C, non è possibile accidentalmente sovraccarico del buffer; verrà ridimensionato automaticamente se la stringa di input è troppo grande.

answer from @oli_obk - ker è la soluzione idiomatica che vedrete il più delle volte. In esso, la stringa è gestita per te e l'interfaccia è molto più pulita.