Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 132 ยท Getting Started

Reading Input

Learn how to read user input in Rust with std::io::stdin, read_line, lines and read_to_string, why the newline stays, how parse works and how to handle bad input safely.

Programs become useful when they react to data they did not contain at compile time: a name typed by a user, numbers piped in from a file, a whole document redirected into the program. In Rust, all of this goes through standard input, usually called stdin. It is a stream of bytes that your program can read one piece at a time.

Rust does not hide the details the way a scripting language does. Reading a line means giving the standard library a String to fill, getting back a Result that says whether reading worked, and then turning the text into a number yourself if you need one. That is a few more words than input() in Python, but every step is explicit, and every failure is something you are forced to think about. This lesson walks through the whole path: reading, trimming, parsing and handling bad input. If you have not met println! yet, read Printing first.

Every example on this page that reads input has a preset in the editor's Input box. In your own terminal you would type the text and press Enter instead, or pipe a file into the program with ./program < data.txt.

Reading one line

The standard library lives in the std crate. Input is in the std::io module, and io::stdin() gives you a handle to the program's standard input. The method read_line appends the next line to a String you provide:

Rust read_line appends a line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Three things are worth noticing here.

  1. The String must be declared mut, and you pass it as &mut line. The method appends to the string, so it needs permission to change it. This is your first taste of mutable borrowing, which gets its own chapter in Borrowing. If you forget mut, the compiler stops you:
Rust Forgetting mut (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The real message is error[E0596]: cannot borrow line as mutable, as it is not declared as mutable, and it even suggests the fix: change the declaration to let mut line. Rust variables are immutable unless you say otherwise; Variables explains why.

  1. read_line returns io::Result<usize>, the number of bytes read. A Result is either Ok(value) or Err(error). Here we call .unwrap(), which returns the value and panics (crashes the program with a message) on an error. That is fine for a small demo and wrong for a real program; we fix it below, and Result covers the idea fully.

  2. The text is "Ferris\n", not "Ferris". read_line keeps the newline character that ended the line. The {line:?} placeholder uses the Debug format, which shows the string with quotes and escape sequences, so you can see the invisible \n. Always use {:?} when you are debugging strings that came from outside.

Removing the newline with trim

Because of that trailing newline, comparing and parsing input directly fails in confusing ways. The fix is to call trim(), which returns a view of the string without leading and trailing whitespace (spaces, tabs, \n and the \r\n that Windows uses):

Rust trim before you use the text

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

trim() does not modify line; it returns a &str that points into it. That is why line.len() still counts the original characters. If you only want to remove the line ending and keep other spaces, use trim_end_matches(['\r', '\n']) or strip_suffix('\n').

Turning text into numbers with parse

Everything you read is text. To get a number you call parse, which tries to convert a &str into any type that implements the FromStr trait: integers, floats, bool, char and more. Rust needs to know which type you want, because "5" could be an i32, a u8 or an f64. You tell it with a type annotation on the variable, or with the turbofish ::<>:

Rust
let a: i32 = "42".parse().unwrap();     // type from the variable
let b = "3.5".parse::<f64>().unwrap();  // type from the turbofish

Leave both out and the compiler asks for help (error[E0284]: type annotations needed, with the hint "consider giving n an explicit type"). The type is part of the question you are asking.

Now combine reading and parsing. This example forgets to trim, so it shows what really happens:

Rust parse fails on the newline (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The program compiles, then panics at run time with called Result::unwrap()on anErr value: ParseIntError { kind: InvalidDigit }. The \n is not a digit. One .trim() fixes it: line.trim().parse().

Handling bad input without crashing

Users type abc, an empty line, or 99999999999. A robust program treats those as normal events. Since parse returns a Result, you can use match to handle both outcomes:

Rust Parse with match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Look at the details:

  • line.clear() empties the string at the start of each round. Because read_line appends, forgetting this makes the string grow and every later parse see old text too.
  • read_line returns Ok(0) at end of input (EOF). That is how a loop knows there is nothing more to read. An empty line, by contrast, returns Ok(1) because of its \n.
  • The error e implements Display, so prints a readable explanation such as invalid digit found in string or number too large to fit in target type. The input 99999999999 is valid digits, but too big for i32, and -3 parses fine because i32 is signed. Try changing the type to u8 or i64 and watch the outcomes change.
  • " 7 " works only because we call trim() first. parse itself is strict: it does not skip spaces.

Reading all lines with lines()

Most programs read until the input ends. The lines() method gives you an iterator that yields one Result<String, io::Error> per line, with the line ending already removed. This is usually nicer than a manual loop:

Rust Summing numbers line by line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

There are two new things in this code.

lock() takes the lock on stdin once and returns a handle that you can read from repeatedly. Plain io::stdin().read_line(...) locks and unlocks on every call, which is perfectly fine for interactive programs but a measurable cost when you read a million lines. The lines() method on Stdin itself (available since Rust 1.62) exists too, so io::stdin().lines() works without the explicit lock(); it locks internally. The lock() plus BufRead form is still common in older code and is useful when you want to hold the lock for several operations.

BufRead is a trait: a named set of methods. A trait's methods are only usable when the trait is in scope, which is why we wrote use std::io::{self, BufRead};. If you forget it with the lock() form, rustc reports that no method named lines is found and suggests importing std::io::BufRead. Traits explains this mechanism.

Reading everything at once

Sometimes you want the whole input as a single string, for example to split it into words regardless of line breaks. read_to_string does exactly that, and it needs Read in scope rather than BufRead:

Rust read_to_string and split_whitespace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

split_whitespace() splits on any run of spaces, tabs and newlines, so blank lines vanish. The map closure parses each word, and collect() gathers the results into a Vec<i32>; the annotation on numbers tells collect and parse which types to use. This pattern is the standard way to read competitive-programming style input.

There is also a shortcut, std::io::read_to_string(io::stdin()) (stable since Rust 1.65), that returns the string directly as an io::Result<String>, and io::stdin().lines() as mentioned above. Use whichever reads best.

Propagating errors with ?

Calling unwrap after every step makes code crash on the first problem. A better habit is to write a function that returns a Result and use the ? operator, which means "if this failed, return the error from the current function now". Here is a function that asks for two integers and adds them:

Rust A fallible helper with question marks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The function's return type Result<i32, Box<dyn Error>> says "an i32, or any kind of error". Both an io::Error and a ParseIntError can be converted into that box automatically by ?. Notice that the compiler infers parse::<i32>() from the return type: n flows into Ok(n), which must be an i32. The third call finds no more input; read_line returns Ok(0) with an empty string, and parsing an empty string fails with cannot parse integer from empty string. Whether an empty read counts as an error is your decision, not the library's. Error handling gets its own chapter, starting with The ? Operator.

Prompts and flushing

Interactive programs often print a prompt on the same line as the answer, using print! (no newline) instead of println!. Rust's stdout is line buffered, which means text without a newline may stay in a buffer and the user does not see the prompt before the program waits for input. Flush the buffer explicitly:

Rust
use std::io::{self, Write};

fn main() {
    print!("Your name: ");
    io::stdout().flush().unwrap(); // show the prompt now
    let mut name = String::new();
    io::stdin().read_line(&mut name).unwrap();
    println!("Hi, {}!", name.trim());
}

This block is read-only because the editor shows the output after the run, not interactively, but in a real terminal the flush is what makes the prompt appear first.

For anything beyond the simplest tools, write a small fn read_line() -> Option<String> helper once and reuse it. It keeps clear, trim and the EOF check in a single place instead of repeated in every loop.

Common mistakes

  • Forgetting mut on the String (error E0596) or forgetting &mut at the call site (a type mismatch error).
  • Parsing without trim(), which fails because of the newline or stray spaces.
  • Not clearing a reused String before read_line, which appends to old text.
  • Treating EOF as an error. Ok(0) is the normal way input ends.
  • Calling unwrap on user input in a real program. A user typing abc should not crash it.
  • Unbounded input. read_to_string reads everything into memory. For huge or hostile input, read line by line or use Read::take to cap the size.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does read_line do with the newline at the end of the line?

    read_line appends the whole line including the line ending. trim() returns a view without the leading and trailing whitespace.
  2. 2. What does read_line return when the input has ended (EOF)?

    At the end of input, read_line reads zero bytes and returns Ok(0). An empty line in the middle of the input returns Ok(1), because of its newline.
  3. 3. Why does let n = "5".parse().unwrap(); fail to compile?

    parse is generic over the target type. Without an annotation like let n: i32 or a turbofish like parse::<i32>(), rustc reports E0284: type annotations needed.
  4. 4. Which line is needed to call .lines() on io::stdin().lock()?

    lines() is a method of the BufRead trait, and trait methods are only available when the trait is in scope.
  5. 5. Why does a loop that calls read_line repeatedly usually start with line.clear()?

    read_line appends. Without clear(), each new line is added after the previous ones and parsing would see the old text as well.

Summary

  • std::io::stdin() is the standard input; read_line(&mut s) appends one line (with its newline) to a mut String and returns io::Result<usize>.
  • Ok(0) means end of input. Call line.clear() between reads when reusing a buffer.
  • trim() removes surrounding whitespace and line endings; do it before comparing or parsing.
  • parse::<T>() converts text to a number or other FromStr type and returns a Result; name the type with an annotation or the turbofish.
  • stdin().lock().lines() (needs BufRead) iterates over lines; read_to_string (needs Read) reads everything at once.
  • Handle bad input with match, or return a Result from a helper and use ?; reserve unwrap for quick demos.
  • Flush stdout with io::stdout().flush() when a print! prompt must appear before the program waits.

Next: The main Function, Arguments and Exit Codes shows what happens around main and how a program reports success or failure to the outside world.