Rust 1.0 中如何读取用户输入的整数?

问题描述 投票:0回答:9

我找到的现有答案都是基于

from_str
(例如高效地从控制台读取用户输入一次),但显然
from_str(x)
在Rust 1.0中已经变成了
x.parse()
。作为新手,考虑到这一变化,应如何调整原始解决方案并不明显。

从 Rust 1.0 开始,从用户那里获取整数输入的最简单方法是什么?

input integer rust user-input
9个回答
70
投票

这是一个包含所有可选类型注释和错误处理的版本,这对于像我这样的初学者可能有用:

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),
    };
}

25
投票

如果您正在寻找一种读取输入的方法,以便在无法访问

text_io
的网站上进行竞争性编程,那么此解决方案适合您。

我使用以下宏从

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);
}


15
投票

可能最简单的部分是使用 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。

另请参阅:


14
投票

以下是一些可能性(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);
    }
}

这些可以让您免去模式匹配的麻烦,而无需依赖额外的库。


4
投票

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."),
    }
}

3
投票

如果您想要简单的语法,您可以创建一个扩展方法:

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(())
}

2
投票

我肯定会使用 Rust-Lang 提供的文件系统

std::fs
(查看更多信息:https://doc.rust-lang.org/stable/std/fs/)但更具体的是 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"));   
}

2
投票

你可以试试这段代码

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 ;
}

0
投票

我认为现在比以前更容易了。

#[macro_use] extern crate text_io;

fn main() {
    print!("Command: ");
    let mut ui: String = read!();

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

您还可以查看 text_io 文档

© www.soinside.com 2019 - 2024. All rights reserved.