4

Reading input from stdin produces a String, but how do I convert it to an integer?

use std::io;

fn main() {
    println!("Type something");

    let mut input = String::new();

    io::stdin()
        .read_line(&mut input)
        .expect("Failed to read line");

    println!("{}", input);
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Gapry
  • 253
  • 1
  • 7
  • 20
  • 4
    You should read the excellent Rust Book, which [specifically covers reading a number from standard input](http://doc.rust-lang.org/book/guessing-game.html). – Shepmaster Jan 22 '15 at 00:13

1 Answers1

16

Use parse:

use std::io;

fn main() {
    println!("Type something");

    let mut line = String::new();

    io::stdin()
        .read_line(&mut line)
        .expect("Failed to read line");

    let input: u32 = line
        .trim()
        .parse()
        .expect("Wanted a number");

    println!("{}", input);
}

Note that parsing a number from a string can fail, so a Result is returned. For this example, we panic on a failure case using expect.

Additionally, read_line leaves the newline from pressing Enter, so trim is used to ignore that before parsing.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    Sidenote: you can call parse on an `&str` to get any type `T` as long as `T` implements the trait `FromStr`. – tolgap Jan 22 '15 at 10:34