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

Hello this year I wrote a new RFC including a lot of threads, posts, others RFCs and pull requests as a reference of the need to have this in this language.

As part of this initiative I published a basic library, you can find the repository in Github.

The point of this RFC is had a basic input macro exactly how did you say.

And essentially it's very basic because the point of this is being simple and ergonomic, I don't cover all the cases, validations and many other things, but you can build your own parser on structures and enums implementing the trait FromStr

I have some examples and if you like it can you leave a comment, react to the RFC or just leave a star into the library or something like that.

Any questions or comments are welcome :slight_smile:

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.