Hello there!
I am here to ask about, how to get user input and convert it to an integer by using parse and trim functions?
The simple way if you don't case about error handling is
let user_input: &str;
let user_input = user_input.parse::<i32>().expect("Invalid input");
if you want to supply a default on invalid input
let user_input: &str;
let default_value: i32;
let user_input = user_input.parse::<i32>().unwrap_or(default_value);
Once you start to care about error handling
let user_input: &str;
let user_input = if let Ok(user_input) = user_input.parse::<i32>() {
user_input
} else {
// error handling
};
You can use any of the integer types instead of i32
in the examples above
2 Likes
To get user input, see the std::io module. A simple example looks like:
use std::{io::stdin, error::Error};
fn main() -> Result<(), Box<dyn Error>> {
let mut input = String::new();
stdin().read_line(&mut input)?;
let num: i32 = input.trim().parse()?;
println!("{} squared is {}", num, num * num);
Ok(())
}
2 Likes
Also work through the guessing game example here. It covers basic string parsing into numbers and concepts related to it on a very basic level.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.