Learn/Rust/3. Reading input and arithmetic
Lesson 3 of 15
Sign in

Rust, lesson 3

Reading input and arithmetic

Your programs in this course read from standard input (stdin) and print to standard output. Rust's standard library puts input tools in the std::io module.

Reading one line

Step by step:

  • use std::io; lets you write io::stdin() instead of std::io::stdin().
  • String::new() makes an empty, growable string. It must be mut because read_line will add text to it.
  • &mut line lends the string to read_line so it can write into it. Lesson 14 explains borrowing properly; for now, read as "you may change this".

2 exercises to try what you just read.

Exercise 1

Split the bill

Press Ctrl Enter or Check to test your code.

Exercise 2

Race timer

Press Ctrl Enter or Check to test your code.

&mut
  • read_line keeps the newline at the end, so trim() removes surrounding whitespace.
  • Reading can fail, so read_line returns a Result. expect gives you the value on success and stops the program with your message on failure.
  • Reading everything at once

    When the input has many numbers spread over lines, it is often simplest to read it all and split on whitespace:

    split_whitespace gives the pieces one at a time. next() returns the next piece wrapped in an Option (it might have run out), and unwrap() takes it out. unwrap is like expect without a custom message.

    Parsing text into numbers

    parse converts a string to another type. It needs to know the target type, which you give with an annotation (let n: i32 = ...) or with the "turbofish" syntax: "42".parse::<i32>(). Parsing returns a Result because the text might not be a number. In lesson 9 you will handle that properly; for now unwrap() is fine.

    Arithmetic

    OperatorMeaning7 ? 2 with integers
    +add9
    -subtract5
    *multiply14
    /divide3
    %remainder1

    Integer division drops the fraction: 7 / 2 is 3. For 3.5, use floats: 7.0 / 2.0, or convert with as f64. Both sides of an operator must have the same type; 5_i32 + 2.0 is a compile error.

    Compound assignment works as you would expect: x += 1, x *= 2. Rust has no ++ or --.

    Numbers have useful methods: n.abs(), n.pow(3), x.sqrt(), x.round(), and a.max(b) / a.min(b).

    Formatting numbers

    Further reading

    • The Rust Book: Programming a guessing game
    • std::io::Stdin
    • str::parse
    • The Rust Book: Numeric operations

    Friends share a restaurant bill equally. Read the bill total (a decimal number) and the number of people (a whole number), separated by whitespace. Print what each person pays with exactly two decimals.

    Sample input:

    Sample output:

    A race timer records a run in whole seconds. Read one integer and print it as H:MM:SS, where minutes and seconds always have two digits.

    Sample input:

    Sample output:

    use std::io;
    
    fn main() {
        let mut line = String::new();
        io::stdin().read_line(&mut line).expect("failed to read");
        let name = line.trim();
        println!("Hello, {name}!");
    }
    let input = io::read_to_string(io::stdin()).unwrap();
    let mut words = input.split_whitespace();
    let a: i64 = words.next().unwrap().parse().unwrap();
    let b: i64 = words.next().unwrap().parse().unwrap();
    println!("{}", a + b);
    println!("{:.2}", 10.0 / 3.0); // 3.33
    println!("{}:{:02}", 7, 5);    // 7:05
    85.00 3
    28.33
    3725
    1:02:05