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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With