Simple way to read input from the terminal (stdio)

there is some way to read input from the terminal efficiently? i'm doing a little bit of competitive programming to train my rust skills, generally i always need to read input from the terminal and them trim it them split and them parse into a int32, this result into my code being a little longer than it should be, there is some way to read input very quickly? like the println! macro but for input instead? here it's my code i don't know a lot about rust soo i'm unsure if i'm doing something wrong:

use std::io;

fn main() {
    let mut buffer = String::new();
    
    io::stdin().read_line(&mut buffer).unwrap();
    
    let mut things: Vec<&str> = buffer.split_whitespace().collect();
    let [a, b] = &things[..] else {panic!("bad input")};
    let a: i32 = a.parse().unwrap();
    let b: i32 = b.parse().unwrap();
    println!("{a}, {b}");
}
1 Like

There's no scanln! or such in std, no.

The best way forward depends on the particulars of the competitive programming venue. Can you use third party crates? Can you have a stash of copy-paste helper functions? Is the goal quickest execution or shortest code length or something else?

AFAICT your goal is "quickest to code". Maybe these will help.

If it's "quickest to execute", macros aren't the way. You'd probably want to write to locked i/o handles and/or handle your own buffering, etc.

1 Like

You can write a generic function to read parsable input from STDIN and then implement FromStr for a newtype containing your respective data.

There was this announcement just recently. Check out the input!() macro...they say how to use it in the announcement. Their docs could use some work.

2 Likes