You can call str::parse(), but you need to make sure that read_line is working. We need a reader:
use std::io;
fn main() {
let reader = io::stdin();
}
stdin reads the global buffer that handles the input stream and also implements the BufRead trait which has the read_line method method. This takes a mutable String as an input buffer and reads all bytes from the stream until a newline byte is reached and appends them to the buffer. The #expect() method unwraps the Result; if it is an Err it will panic with the message and the cause.
use std::io;
fn main() {
let reader = io::stdin();
let mut input_text = String::new();
reader.read_line(&mut input_text).expect("failed to read line");
}
We now have the input text that we want to convert into an i32. This is where str::parse() will work for us, as long as we give it a type to parse to. str::trim() is necessary because read_line includes the newline byte the buffer
use std::io;
fn main() {
let reader = io::stdin();
let mut input_text = String::new();
reader.read_line(&mut input_text).expect("failed to read line");
let input = input_text.trim().parse::<i32>();
}
We're not done yet, we still need to ensure that we successfully parsed the input using pattern matching. All the code you need to convert your original input buffer into a usable integer is:
use std::io;
fn main() {
let reader = io::stdin();
let mut input_text = String::new();
reader.read_line(&mut input_text).expect("failed to read line");
let input_opt = input_text.trim().parse::<i32>();
let input_int = match input_opt {
Ok(input_int) => input_int,
Err(e) => {
println!("please input a number ({})", e);
return;
}
};
println!("{}", input_int);
}
This compiles without errors or warnings.
Answer from rouma7 on Stack OverflowYou can call str::parse(), but you need to make sure that read_line is working. We need a reader:
use std::io;
fn main() {
let reader = io::stdin();
}
stdin reads the global buffer that handles the input stream and also implements the BufRead trait which has the read_line method method. This takes a mutable String as an input buffer and reads all bytes from the stream until a newline byte is reached and appends them to the buffer. The #expect() method unwraps the Result; if it is an Err it will panic with the message and the cause.
use std::io;
fn main() {
let reader = io::stdin();
let mut input_text = String::new();
reader.read_line(&mut input_text).expect("failed to read line");
}
We now have the input text that we want to convert into an i32. This is where str::parse() will work for us, as long as we give it a type to parse to. str::trim() is necessary because read_line includes the newline byte the buffer
use std::io;
fn main() {
let reader = io::stdin();
let mut input_text = String::new();
reader.read_line(&mut input_text).expect("failed to read line");
let input = input_text.trim().parse::<i32>();
}
We're not done yet, we still need to ensure that we successfully parsed the input using pattern matching. All the code you need to convert your original input buffer into a usable integer is:
use std::io;
fn main() {
let reader = io::stdin();
let mut input_text = String::new();
reader.read_line(&mut input_text).expect("failed to read line");
let input_opt = input_text.trim().parse::<i32>();
let input_int = match input_opt {
Ok(input_int) => input_int,
Err(e) => {
println!("please input a number ({})", e);
return;
}
};
println!("{}", input_int);
}
This compiles without errors or warnings.
The input includes a newline at the end, as explained in the documentation for read_line. This causes from_str() to fail. Using std::str::trim() and changing this:
let input: Result<i32, _> = input_text.parse();
into this:
let input: Result<i32, _> = input_text.trim().parse();
seems to work.
Videos
I wanted to make a simple calculator where the user inputs 2 numbers and it does the operation then shows them the answer. I was wondering how to I convert an input string to an int where I can then perform the operations.
You can directly convert to an int using the str::parse::<T>() method, which returns a Result containing the int.
let my_string = "27".to_string(); // `parse()` works with `&str` and `String`!
let my_int = my_string.parse::<i32>().unwrap();
You can either specify the type to parse to with the turbofish operator (::<>) as shown above or via explicit type annotation:
let my_int: i32 = my_string.parse().unwrap();
Since parse() returns a Result, it will either be an Err if the string couldn't be parsed as the type specified (for example, the string "peter" can't be parsed as i32), or an Ok with the value in it.
let my_u8: u8 = "42".parse().unwrap();
let my_u32: u32 = "42".parse().unwrap();
// or, to be safe, match the `Err`
match "foobar".parse::<i32>() {
Ok(n) => do_something_with(n),
Err(e) => weep_and_moan(),
}
str::parse::<u32> returns a Result<u32, core::num::ParseIntError> and Result::unwrap "Unwraps a result, yielding the content of an Ok [or] panics if the value is an Err, with a panic message provided by the Err's value."
str::parse is a generic function, hence the type in angle brackets.
Is this really the only way to get a &str into an int?
int::parse_bytes("10".to_string().into_bytes().as_slice(), 10)It seems a little ridiculous that one has to turn it into a String, then Vec<u8>, then &[u8]. Maybe this is a lack of documentation but I feel like there must be a more straightforward method.