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.
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.
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.
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); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With