Skip to content

Read Input from the Console

The Course
•
28 min study

So far every value has been written into the program itself. A useful planner has to take its sessions from the person using it. Standard input, or stdin, is the stream of text supplied to a running program: typed at a terminal, or piped in from a file. In these lessons, fill the stdin box below a playground before pressing Run. The browser sends that text and then closes the stream, as if you had reached the end of a file.

io::stdin().read_line(&mut input) reads one line and appends it to a String you own. It needs a mutable borrow, &mut input, for the same reason the functions on Day 3 did: it changes text that belongs to the caller. Reading can fail, so it returns a Result. On success, the Ok value is the number of bytes read, and Ok(0) means there was nothing left to read.

Predict and run

The input has extra spaces. What does the program print?

Predict, then run Rust
use std::io;

fn main() {
    let mut input = String::new();
    match io::stdin().read_line(&mut input) {
        Ok(0) => println!("No input"),
        Ok(_) => println!("Topic: {}", input.trim()),
        Err(_) => println!("Could not read input"),
    }
}
Rust
Check your prediction
Text
Topic: Rust

trim() borrows the text without the whitespace at either end, including the newline. It does not change input; it returns a view, a &str, into the middle of it. use std::io; at the top lets you write io::stdin() instead of the full path std::io::stdin().

Clear the stdin box and run: you get No input. Then enter only a blank line and run again: you get Topic: with nothing after it. Predict why before reading on.

What read_line actually stores

The line in input still has its newline. Debug formatting with {input:?} shows the text in quotes with invisible characters spelled out, which makes it the best tool for seeing exactly what you read.

Look at the raw line Rust
use std::io;

fn main() {
    let mut input = String::new();
    match io::stdin().read_line(&mut input) {
        Ok(bytes) => {
            println!("Read {bytes} bytes: {input:?}");
            println!("Trimmed: {:?}", input.trim());
        }
        Err(_) => println!("Could not read input"),
    }
}
Rust
Text
Read 9 bytes: "  Rust  \n"
Trimmed: "Rust"

A blank line is not the end of input: it contains one byte, the newline \n, so it produces Ok(1). Only a closed stream with nothing left produces Ok(0). That is why checking Ok(0) alone misses blank lines, and why the dependable test is whether the trimmed text is empty. The same newline is why "45\n".parse::<u32>() fails while "45\n".trim().parse::<u32>() succeeds.

read_line appends

read_line adds to whatever is already in the String. Reading a second line into the same variable without clearing it gives you both lines together, a mistake that is easy to make and confusing to see.

Clear the buffer between reads Rust
use std::io;

fn main() {
    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap_or(0);
    println!("First: {input:?}");
    io::stdin().read_line(&mut input).unwrap_or(0);
    println!("Without clear: {input:?}");
    input.clear();
    io::stdin().read_line(&mut input).unwrap_or(0);
    println!("After clear: {input:?}");
}
Loops Traits
Text
First: "Loops\n"
Without clear: "Loops\nTraits\n"
After clear: ""

After clear() the third read finds the stream already used up, so it adds nothing. unwrap_or(0) here just ignores a read error to keep the example short. When you need many lines, Day 7 shows a loop that hands you each line as a fresh String.

Trim, then decide

Treat every line from stdin as untrusted text. Trim it first, then check for empty text, then parse, then check the range. Each step gets its own message.

Practice

Exercise

Your turn

Handle empty input and a blank line with the same message, Enter a topic. Otherwise print the trimmed topic, such as Topic: Rust. Try the prefilled blank line, then clear the input box, then type a topic with spaces around it.

Your working space Rust
use std::io;

fn main() {
    let mut input = String::new();
    match io::stdin().read_line(&mut input) {
        Ok(_) => println!("Topic: {}", input.trim()),
        Err(_) => println!("Could not read input"),
    }
}
Hint 1: the idea

On success, both an empty input and a blank line leave no text after trimming.

Hint 2: a first step

Bind let topic = input.trim(); inside the Ok arm, then check topic.is_empty().

Worked solution
Run the solution Rust
use std::io;

fn main() {
    let mut input = String::new();
    match io::stdin().read_line(&mut input) {
        Ok(_) => {
            let topic = input.trim();
            if topic.is_empty() {
                println!("Enter a topic");
            } else {
                println!("Topic: {topic}");
            }
        }
        Err(_) => println!("Could not read input"),
    }
}
Text
Enter a topic

An empty String and one containing only spaces and a newline both trim to an empty slice, so one test covers both cases and you no longer need a separate Ok(0) arm. The checkpoint adds parsing and a range check on top of exactly this structure.

Was this article helpful?

Your response is saved on this device.