I am writing a paper about how python and Rust differ when used on coding challenges. I have to preface this with the fact that this is my first Rust program ever. So sorry if I'm doing some weird stuff. However, when I am looping through some input in Rust, I get this error:
2
4
1
2
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }', src\main.rs:24:14
Here is my code:
use std::fs::File;
use std::io::{Read};
use std::cmp;
fn main() {
let mut file = File::open("C:\\Users\\isaak\\OneDrive\\skewl\\Fall 2019\\Operating Systems\\rustyboi\\src\\bus.txt").expect("Can't Open File");
let mut contents = String::new();
file.read_to_string(&mut contents).expect("Can't Read File");
let tokens:Vec<&str> = contents.split("\n").collect();
let l1:Vec<&str> = tokens[0].split(" ").collect();
let _n = l1[0];
let w = l1[1];
//println!("{}", w);
let l2 = tokens[1].split(" ");
let mut k = 0;
let mut maxed = 0;
let mut mined = 0;
for item in l2 { // in range n
println!("{}", item);
k += item.parse::<i32>().unwrap();
maxed = cmp::max(k, maxed);
mined = cmp::min(k, mined);
}
println!("{}", cmp::max(w.parse::<i32>().unwrap() - maxed + mined.abs() + 1, 0));
}
The file that it is looking at only contains this:
4 10
2 4 1 2
I am not sure how I could be getting that error on the k+= part in the for loop when the printed value is definitely a number. Anyway, here is a link to the coding challenge in case you are curious: https://codeforces.com/contest/978/problem/E
The working solution in Rust Playground: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=ed17ea24cfcf4b45549846a5c9f1edfd
Your file contains \r\n
ends of line ("4 10\r\n2 4 1 2\r\n"
), and after splitting by only \n
there is \r
at the end of each line, therefore parsing fails (\r
cannot be parsed into integer).
lines()
instead of split("\n")
as a cross-platform solution.split_whitespace()
instead of split(" ")
.