Rust 不能正确读取整数输入 [英] Rust not properly reading integer input

查看:67
本文介绍了Rust 不能正确读取整数输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一个简单的程序来测试我的 Rust 技能,该程序从一行输入中读取多个整数.它编译正确,但不幸的是,当它收到 1 2 3 的输入时,它会恐慌,说输入不是一个有效的整数.有人可以解释一下原因吗,并解释一下我如何修复我的程序?

I'm trying to test out my Rust skills with a simple program that reads multiple integers from a single line of input. It compiles correctly, but unfortunately when it receives the input of 1 2 3, it panics, saying that the input wasn't a valid integer. Can someone please explain the reason for this, and also provide an explanation as to how I can fix my program?

use std::io;

fn main() {
    let mut string = String::new();
    io::stdin().read_line(&mut string);

    let int_vec: Vec<u32> = string.split(" ")
        .map(|x| x.parse::<u32>().expect("Not an integer!"))
        .collect();

     for i in (0..int_vec.len()).rev() {
         print!("{} ", int_vec[i]);
     }
}

推荐答案

除了 Dogberts 的回答之外...看看您将来如何自己使用迭代器调试此类问题可能会有所帮助.

In addition to Dogberts answer... it might be helpful to see how you might be able to debug this sort of issue with an iterator yourself in future.

Iterator trait 公开了一个 inspect 函数,您可以使用它来检查每个项目.将您的代码转换为在每个地图之前和之后使用 inspect 会导致:

The Iterator trait exposes an inspect function that you can use to inspect each item. Converting your code to use inspect both before and after each map results in:

let int_vec: Vec<u32> = string.split(" ")
.inspect(|x| println!("About to parse: {:?}", x))
.map(|x| {
    x.parse::<u32>()
        .expect("Not an integer!")
})
.inspect(|x| println!("Parsed {:?} successfully!", x))
.collect();

输出:

1 2 3
About to parse: "1"
Parsed 1 successfully!
About to parse: "2"
Parsed 2 successfully!
About to parse: "3\n"

thread '<main>' panicked at 'Not an integer!...

注意当它到​​达数字 3 时它试图解析什么.

Notice what its attempting to parse when it gets to the number 3.

当然,您可以自行检查 string.inspect 在涉及迭代器时很方便.

Of course, you can inspect string all by itself. inspect is handy though for when iterators are involved.

这篇关于Rust 不能正确读取整数输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆