Editor\'s note: This question refers to parts of Rust that predate Rust 1.0, but the general concept is still valid in Rust 1.0.
I intend to
from https://doc.rust-lang.org/book/ch02-00-guessing-game-tutorial.html#processing-a-guess
use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("Failed to read line");
println!("You guessed: {}", guess);
}
While there are many different ways of doing this in rust I think this is the simplest to implement.
use std::io;
// ...
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
println!("Your input was `{}`", input);
// ...
Editor's note: This answer predates Rust 1.0. Please see the other answers for modern solutions.
Uh... After many trials and errors, I've found a solution.
I'd still like to see a better solution so I'm not going to accept my own solution.
The code below prints exactly what the user inputs.
mod tokenizer {
pub fn read () -> ~[int] {
let reader = io::stdin();
let mut bytes: ~[int] = ~[];
loop {
let byte: int = reader.read_byte();
if byte < 0 {
return bytes;
}
bytes += [byte];
}
}
}
fn main () {
let bytes: ~[int] = tokenizer::read();
for bytes.each |byte| {
io::print(#fmt("%c", *byte as char));
}
}
Editor's note: This answer predates Rust 1.0. Please see the other answers for modern solutions.
In Rust 0.4, use the ReaderUtil
trait to access the read_line
function. Note that you need to explicitly cast the value to a trait type, eg, reader as io::ReaderUtil
fn main() {
let mut allLines = ~[];
let reader = io::stdin();
while !reader.eof() {
allLines.push((reader as io::ReaderUtil).read_line());
}
for allLines.each |line| {
io::println(fmt!("%s", *line));
}
}
The question is to read lines from stdin and return a vector. On Rust 1.7:
fn readlines() -> Vec<String> {
use std::io::prelude::*;
let stdin = std::io::stdin();
let v = stdin.lock().lines().map(|x| x.unwrap()).collect();
v
}
This is what I have come up with (with some help from the friendly people in the #rust IRC channel on irc.mozilla.org):
use core::io::ReaderUtil;
fn read_lines() -> ~[~str] {
let mut all_lines = ~[];
for io::stdin().each_line |line| {
// each_line provides us with borrowed pointers, but we want to put
// them in our vector, so we need to *own* the lines
all_lines.push(line.to_owned());
}
all_lines
}
fn main() {
let all_lines = read_lines();
for all_lines.eachi |i, &line| {
io::println(fmt!("Line #%u: %s", i + 1, line));
}
}
And proof that it works :)
$ rustc readlines.rs
$ echo -en 'this\nis\na\ntest' | ./readlines
Line #1: this
Line #2: is
Line #3: a
Line #4: test
There is a crate named proconio.