Rust input/output: Difference between revisions

From wikinotes
Line 20: Line 20:
use std::io::BufRead;
use std::io::BufRead;


let mut input: Vec<String> = Vec::new();
let stdin = io::stdin();
let stdin = io::stdin();
let handle = stdin.lock();
let handle = stdin.lock();
for result in handle.lines() {
let input: Vec<String> = handle
     match result {
    .lines()
        Ok(line) => input.push(line),
     .map(|res| res.unwrap_or_default())
        Err(_) => break,
    .collect();
    }
print!("START\n{}\nFINISH\n", input.join("\n"));
}
print!("START\n{}\nFINISH", input.join("\n"));
</syntaxhighlight>
</syntaxhighlight>



Revision as of 06:41, 9 February 2023

Documentation

std::fs https://doc.rust-lang.org/std/fs/index.html

Stdin, Stdout, Stderr

println!("out");   // write to stdout
eprintln!("err");  // write to stderr

read from stdin (wait indefinitely if nothing is written)

use std::io;
use std::io::BufRead;

let stdin = io::stdin();
let handle = stdin.lock();
let input: Vec<String> = handle
    .lines()
    .map(|res| res.unwrap_or_default())
    .collect();
print!("START\n{}\nFINISH\n", input.join("\n"));

TODO:

read from stdin, checking if it's a tty or a pipe

User Input

let name = String::new();
io::stdin().read_line(&mut name);

Files