如何在 Rust 1.0 中读取用户输入的整数?
How to read an integer input from the user in Rust 1.0?
我找到的现有答案都是基于from_str
(例如Reading in user input from console once efficiently),但显然from_str(x)
在Rust 1.0中变成了x.parse()
。作为新手,考虑到这一变化,应该如何调整原始解决方案并不明显。
从 Rust 1.0 开始,从用户那里获取整数输入的最简单方法是什么?
可能最简单的部分是使用 text_io crate 并写入:
#[macro_use]
extern crate text_io;
fn main() {
// read until a whitespace and try to convert what was read into an i32
let i: i32 = read!();
println!("Read in: {}", i);
}
如果您需要同时读取多个值,您可能需要每晚使用 Rust。
另请参阅:
- Is there a way to check that the user entered an integer with text_io's read!() macro?
parse
大致相同;现在是read_line
不愉快
use std::io;
fn main() {
let mut s = String::new();
io::stdin().read_line(&mut s).unwrap();
match s.trim_right().parse::<i32>() {
Ok(i) => println!("{} + 5 = {}", i, i + 5),
Err(_) => println!("Invalid number."),
}
}
这是一个包含所有可选类型注释和错误处理的版本,可能对像我这样的初学者有用:
use std::io;
fn main() {
let mut input_text = String::new();
io::stdin()
.read_line(&mut input_text)
.expect("failed to read from stdin");
let trimmed = input_text.trim();
match trimmed.parse::<u32>() {
Ok(i) => println!("your integer input: {}", i),
Err(..) => println!("this was not an integer: {}", trimmed),
};
}
这里有一些可能性(Rust 1.7):
use std::io;
fn main() {
let mut n = String::new();
io::stdin()
.read_line(&mut n)
.expect("failed to read input.");
let n: i32 = n.trim().parse().expect("invalid input");
println!("{:?}", n);
let mut n = String::new();
io::stdin()
.read_line(&mut n)
.expect("failed to read input.");
let n = n.trim().parse::<i32>().expect("invalid input");
println!("{:?}", n);
let mut n = String::new();
io::stdin()
.read_line(&mut n)
.expect("failed to read input.");
if let Ok(n) = n.trim().parse::<i32>() {
println!("{:?}", n);
}
}
这些使您无需依赖额外的库即可进行模式匹配。
如果您正在寻找一种方法来读取输入,以便在无法访问 text_io
的网站(例如 codeforces)上进行竞争性编程,此解决方案适合您。
我使用以下宏从 stdin
中读取不同的值:
#[allow(unused_macros)]
macro_rules! read {
($out:ident as $type:ty) => {
let mut inner = String::new();
std::io::stdin().read_line(&mut inner).expect("A String");
let $out = inner.trim().parse::<$type>().expect("Parsable");
};
}
#[allow(unused_macros)]
macro_rules! read_str {
($out:ident) => {
let mut inner = String::new();
std::io::stdin().read_line(&mut inner).expect("A String");
let $out = inner.trim();
};
}
#[allow(unused_macros)]
macro_rules! read_vec {
($out:ident as $type:ty) => {
let mut inner = String::new();
std::io::stdin().read_line(&mut inner).unwrap();
let $out = inner
.trim()
.split_whitespace()
.map(|s| s.parse::<$type>().unwrap())
.collect::<Vec<$type>>();
};
}
使用方法如下:
fn main(){
read!(x as u32);
read!(y as f64);
read!(z as char);
println!("{} {} {}", x, y, z);
read_vec!(v as u32); // Reads space separated integers and stops when newline is encountered.
println!("{:?}", v);
}
如果你想要一个简单的语法,你可以创建一个扩展方法:
use std::error::Error;
use std::io;
use std::str::FromStr;
trait Input {
fn my_read<T>(&mut self) -> io::Result<T>
where
T: FromStr,
T::Err: Error + Send + Sync + 'static;
}
impl<R> Input for R where R: io::Read {
fn my_read<T>(&mut self) -> io::Result<T>
where
T: FromStr,
T::Err: Error + Send + Sync + 'static,
{
let mut buff = String::new();
self.read_to_string(&mut buff)?;
buff.trim()
.parse()
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
}
}
// Usage:
fn main() -> io::Result<()> {
let input: i32 = io::stdin().my_read()?;
println!("{}", input);
Ok(())
}
我肯定会使用 Rust-Lang 提供的文件系统 std::fs
(查看更多信息:https://doc.rust-lang.org/stable/std/fs/) But more particularly https://doc.rust-lang.org/stable/std/fs/fn.read_to_string.html
假设您只想读取文本文件的输入,试试这个:
use std::fs
or
use std::fs::read_to_string
fn main() {
println!("{}", fs::read_to_string("input.txt"));
}
你可以试试这段代码
fn main() {
let mut line = String::new();
// read input line string and store it into line
std::io::stdin().read_line(&mut line).unwrap();
// convert line to integer
let number : i32 = line.trim().parse().unwrap();
println!("Your number {}",number);
}
现在你可以编写一个函数来获取用户输入并像下面这样每次都使用它
fn main() {
let first_number = get_input();
let second_number = get_input();
println!("Summation : {}",first_number+second_number);
}
fn get_input() -> i32{
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let number : i32 = line.trim().parse().unwrap();
return number ;
}
我找到的现有答案都是基于from_str
(例如Reading in user input from console once efficiently),但显然from_str(x)
在Rust 1.0中变成了x.parse()
。作为新手,考虑到这一变化,应该如何调整原始解决方案并不明显。
从 Rust 1.0 开始,从用户那里获取整数输入的最简单方法是什么?
可能最简单的部分是使用 text_io crate 并写入:
#[macro_use]
extern crate text_io;
fn main() {
// read until a whitespace and try to convert what was read into an i32
let i: i32 = read!();
println!("Read in: {}", i);
}
如果您需要同时读取多个值,您可能需要每晚使用 Rust。
另请参阅:
- Is there a way to check that the user entered an integer with text_io's read!() macro?
parse
大致相同;现在是read_line
不愉快
use std::io;
fn main() {
let mut s = String::new();
io::stdin().read_line(&mut s).unwrap();
match s.trim_right().parse::<i32>() {
Ok(i) => println!("{} + 5 = {}", i, i + 5),
Err(_) => println!("Invalid number."),
}
}
这是一个包含所有可选类型注释和错误处理的版本,可能对像我这样的初学者有用:
use std::io;
fn main() {
let mut input_text = String::new();
io::stdin()
.read_line(&mut input_text)
.expect("failed to read from stdin");
let trimmed = input_text.trim();
match trimmed.parse::<u32>() {
Ok(i) => println!("your integer input: {}", i),
Err(..) => println!("this was not an integer: {}", trimmed),
};
}
这里有一些可能性(Rust 1.7):
use std::io;
fn main() {
let mut n = String::new();
io::stdin()
.read_line(&mut n)
.expect("failed to read input.");
let n: i32 = n.trim().parse().expect("invalid input");
println!("{:?}", n);
let mut n = String::new();
io::stdin()
.read_line(&mut n)
.expect("failed to read input.");
let n = n.trim().parse::<i32>().expect("invalid input");
println!("{:?}", n);
let mut n = String::new();
io::stdin()
.read_line(&mut n)
.expect("failed to read input.");
if let Ok(n) = n.trim().parse::<i32>() {
println!("{:?}", n);
}
}
这些使您无需依赖额外的库即可进行模式匹配。
如果您正在寻找一种方法来读取输入,以便在无法访问 text_io
的网站(例如 codeforces)上进行竞争性编程,此解决方案适合您。
我使用以下宏从 stdin
中读取不同的值:
#[allow(unused_macros)]
macro_rules! read {
($out:ident as $type:ty) => {
let mut inner = String::new();
std::io::stdin().read_line(&mut inner).expect("A String");
let $out = inner.trim().parse::<$type>().expect("Parsable");
};
}
#[allow(unused_macros)]
macro_rules! read_str {
($out:ident) => {
let mut inner = String::new();
std::io::stdin().read_line(&mut inner).expect("A String");
let $out = inner.trim();
};
}
#[allow(unused_macros)]
macro_rules! read_vec {
($out:ident as $type:ty) => {
let mut inner = String::new();
std::io::stdin().read_line(&mut inner).unwrap();
let $out = inner
.trim()
.split_whitespace()
.map(|s| s.parse::<$type>().unwrap())
.collect::<Vec<$type>>();
};
}
使用方法如下:
fn main(){
read!(x as u32);
read!(y as f64);
read!(z as char);
println!("{} {} {}", x, y, z);
read_vec!(v as u32); // Reads space separated integers and stops when newline is encountered.
println!("{:?}", v);
}
如果你想要一个简单的语法,你可以创建一个扩展方法:
use std::error::Error;
use std::io;
use std::str::FromStr;
trait Input {
fn my_read<T>(&mut self) -> io::Result<T>
where
T: FromStr,
T::Err: Error + Send + Sync + 'static;
}
impl<R> Input for R where R: io::Read {
fn my_read<T>(&mut self) -> io::Result<T>
where
T: FromStr,
T::Err: Error + Send + Sync + 'static,
{
let mut buff = String::new();
self.read_to_string(&mut buff)?;
buff.trim()
.parse()
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
}
}
// Usage:
fn main() -> io::Result<()> {
let input: i32 = io::stdin().my_read()?;
println!("{}", input);
Ok(())
}
我肯定会使用 Rust-Lang 提供的文件系统 std::fs
(查看更多信息:https://doc.rust-lang.org/stable/std/fs/) But more particularly https://doc.rust-lang.org/stable/std/fs/fn.read_to_string.html
假设您只想读取文本文件的输入,试试这个:
use std::fs
or
use std::fs::read_to_string
fn main() {
println!("{}", fs::read_to_string("input.txt"));
}
你可以试试这段代码
fn main() {
let mut line = String::new();
// read input line string and store it into line
std::io::stdin().read_line(&mut line).unwrap();
// convert line to integer
let number : i32 = line.trim().parse().unwrap();
println!("Your number {}",number);
}
现在你可以编写一个函数来获取用户输入并像下面这样每次都使用它
fn main() {
let first_number = get_input();
let second_number = get_input();
println!("Summation : {}",first_number+second_number);
}
fn get_input() -> i32{
let mut line = String::new();
std::io::stdin().read_line(&mut line).unwrap();
let number : i32 = line.trim().parse().unwrap();
return number ;
}