Skip to content

Commit e5d1084

Browse files
committed
added stdio example
1 parent ffda5c1 commit e5d1084

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,4 @@ in a controlled repository now.
4141
* `charcast.rs`: character / number casting examples
4242
* `lower.rs`: boring character lowercase example
4343
* `stringchars.rs`: string ←→ chars conversion examples
44+
* `stdio.rs`: stdio usage example

stdio.rs

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/// Use `Write` so that `writeln!()` and `write!()` work.
2+
/// Use `BufRead` so that `stdin.read_line()` works.
3+
use std::io::{self, Write, BufRead};
4+
5+
fn main() {
6+
// Get a handle to stdout. Note that we are not bothering to lock it, because we don't care
7+
// about performance and there's no `BufWrite` trait.
8+
let mut stdout = io::stdout();
9+
// This could just as easily have been `println!()`.
10+
writeln!(stdout, "Trying some stuff").unwrap();
11+
// Print a prompt and leave the cursor there.
12+
write!(stdout, "> ").unwrap();
13+
// Without this the prompt won't appear until way late.
14+
stdout.flush().unwrap();
15+
// Get a handle to stdin. Note that this must be a separate step from locking, because the
16+
// locking borrows the handle.
17+
let stdin = io::stdin();
18+
// Get a locked `StdinLocked` guard. This obeys `BufRead`.
19+
let mut stdin = stdin.lock();
20+
// Make a placeholder to read a line of text into.
21+
let mut msg = String::new();
22+
// Read a line of text as a side effect in `msg`.
23+
let _ = stdin.read_line(&mut msg).unwrap();
24+
// Show the line, trimming off the line ending (and any whitespace).
25+
eprintln!("Got {}", msg.trim_end());
26+
}

0 commit comments

Comments
 (0)