Looking for a better way to get input from a Online Judge System

I am trying to use Rustlang on a Online Judge System, and it should get input from commond lines, my solution is as follow, and I am looking for better way to get input from commond lines:

use std::io::Read;

fn get_input(){
    let mut buffer=String::new();
    std::io::stdin().read_to_string(&mut buffer).unwrap();
    let mut ans:Vec<Vec<i32>>=Vec::new();
    for li in buffer.lines(){
        let nums= li.trim().split(' ').map(|e| e.parse::<i32>().unwrap()).collect();
        ans.push(nums);
    }
    println!("{:?}",ans);
}

fn main() {
    get_input();
}

The input will looks like this:

5 6 0 2
1 2 1 5 3
0 1 1
0 2 2
0 3 1
1 2 1
2 4 1
3 4 1

And I want to the output looks like:

[[5, 6, 0, 2],
 [1, 2, 1, 5, 3],
 [0, 1, 1],
 [0, 2, 2],
 [0, 3, 1],
 [1, 2, 1], 
 [2, 4, 1], 
 [3, 4, 1]]

A sample exame question is as follows:

If I was solving that problem, I would be starting it like this:

use std::io::Read;

fn main() {
    let mut buffer = String::new();
    std::io::stdin().read_to_string(&mut buffer).unwrap();
    let mut input = buffer.split_ascii_whitespace();
    
    let n: usize = input.next().unwrap().parse().unwrap();
    let m: usize = input.next().unwrap().parse().unwrap();
    let c1: usize = input.next().unwrap().parse().unwrap();
    let c2: usize = input.next().unwrap().parse().unwrap();
    
    let mut num_rescue_teams = Vec::with_capacity(n);
    for _ in 0..n {
        num_rescue_teams.push(input.next().unwrap().parse::<u32>().unwrap());
    }
    
    let mut graph = /* some custom graph type */;
    
    for _ in 0..m {
        let from: usize = input.next().unwrap().parse().unwrap();
        let to: usize = input.next().unwrap().parse().unwrap();
        let length: u32 = input.next().unwrap().parse().unwrap();
        
        // add edge to graph data structure
    }
}

OK, thanks for your help, I've learned. :smiley:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.