Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read user input in Rust?

Tags:

io

input

rust

I intend to make a tokenizer. I need to read every line the user types and stop reading once the user presses Ctrl + D.

I searched around and only found one example on Rust IO which does not even compile. I looked at the io module's documentation and found that the read_line() function is part of the ReaderUtil interface, but stdin() returns a Reader instead.

The code that I would like would essentially look like the following in C++:

vector<string> readLines () {     vector<string> allLines;     string line;      while (cin >> line) {         allLines.push_back(line);     }      return allLines; } 

This question refers to parts of Rust that predate Rust 1.0, but the general concept is still valid in Rust 1.0.

like image 807
Jimmy Lu Avatar asked Nov 27 '12 07:11

Jimmy Lu


People also ask

What is read user input?

Input refers to text written by the user read by the program. Input is always read as a string. For reading input, we use the Scanner tool that comes with Java. The tool can be imported for use in a program by adding the command import java.

How do you pause in Rust?

One way to pause your program, for some particular time is by using sleep() which takes Duration struct as an input. This program should pause for 1 second and then terminate.


1 Answers

Rust 1.x (see documentation):

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

Rust 0.10–0.12 (see documentation):

use std::io;  fn main() {     for line in io::stdin().lines() {         print!("{}", line.unwrap());     } } 

Rust 0.9 (see 0.9 documentation):

use std::io; use std::io::buffered::BufferedReader;  fn main() {     let mut reader = BufferedReader::new(io::stdin());     for line in reader.lines() {         print(line);     } } 

Rust 0.8:

use std::io;  fn main() {     let lines = io::stdin().read_lines();     for line in lines.iter() {         println(*line);     } } 

Rust 0.7:

use std::io;  fn main() {     let lines = io::stdin().read_lines();     for lines.iter().advance |line| {         println(*line);     } } 
like image 157
robinst Avatar answered Oct 06 '22 05:10

robinst