如何使用文件中的数字列表进行简单数学运算并在Rust中打印出结果? [英] How to do simple math with a list of numbers from a file and print out the result in Rust?

查看:172
本文介绍了如何使用文件中的数字列表进行简单数学运算并在Rust中打印出结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

use std::fs::File;
use std::io::prelude::*;
use std::io::BufReader;
use std::iter::Iterator;

fn main() -> std::io::Result<()> {
    let file = File::open("input")?; // file is input
    let mut buf_reader = BufReader::new(file);

    let mut contents = String::new();
    buf_reader.read_to_string(&mut contents)?;

    for i in contents.parse::<i32>() {
        let i = i / 2;
        println!("{}", i);
    }

    Ok(())
}

数字列表:

50951
69212
119076
124303
95335
65069
109778
113786
124821
103423
128775
111918
138158
141455
92800
50908
107279
77352
129442
60097
84670
143682
104335
105729
87948
59542
81481
147508

推荐答案

BufRead::lines 逐行处理文本:

str::parse::<i32> can only parse a single number at a time, so you will need to split the text first and then parse each number one by one. For example if you have one number per line and no extra whitespace, you can use BufRead::lines to process the text line by line:

use std::fs::File;
use std::io::{BufRead, BufReader};

fn main() -> std::io::Result<()> {
    let file = File::open("input")?; // file is input
    let mut buf_reader = BufReader::new(file);

    for line in buf_reader.lines() {
        let value = line?
            .parse::<i32>()
            .expect("Not able to parse: Content is malformed !");

        println!("{}", value / 2);
    }

    Ok(())
}

作为额外的好处,这避免了将整个文件读入内存,如果文件很大,这可能很重要.

As an extra bonus this avoids reading the whole file into memory, which can be important if the file is big.

这篇关于如何使用文件中的数字列表进行简单数学运算并在Rust中打印出结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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