Reading input (stdin)

Read what you type in the IDE's Input tab with read_line or lines().

Runs in Zerethon IDE · Rust 1.87 Official Rust documentation ↗

A run cannot ask questions while it runs. Type the program's input in the Input tab before you press Run; the program reads it from std::io::stdin().

main.rs
use std::io;

fn main() {
    let mut name = String::new();
    io::stdin().read_line(&mut name).unwrap();
    let mut line = String::new();
    io::stdin().read_line(&mut line).unwrap();
    let nums: Vec<i32> = line.split_whitespace().map(|n| n.parse().unwrap()).collect();
    println!("Hello, {}! {} + {} = {}", name.trim(), nums[0], nums[1], nums[0] + nums[1]);
}

Input (stdin)

Ada
3 4

Output

Hello, Ada! 3 + 4 = 7
main.rs
use std::io::{self, BufRead};

fn main() {
    let mut total = 0;
    for line in io::stdin().lock().lines() {
        let line = line.unwrap();
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        match line.parse::<i32>() {
            Ok(n) => total += n,
            Err(_) => println!("skipped {line}"),
        }
    }
    println!("total: {total}");
}

Input (stdin)

5
10
x
15

Output

skipped x
total: 30
Reading every line until the input ends.
  • read_line keeps the newline at the end; call .trim() before comparing or parsing.
  • With no input left, read_line returns Ok(0) and leaves the string empty — parse().unwrap() on it then stops the program with ParseIntError { kind: Empty }.

Related topics

Official references