Suppose I expect a line with 3 integers from stdin. What's the easiest way to read and parse them? What's the Rust equivalent of a, b, c = map(int, input().split())
in Python or scanf("%d %d %d", &a, &b, &c);
in C?
The best way I came up with was something like:
let mut line = String::new();
io::stdin().read_line(&mut line).unwrap();
let parts: Vec<&str> = line.split_whitespace().collect();
let a: i32 = parts[0].parse().unwrap();
let b: i32 = parts[1].parse().unwrap();
let c: i32 = parts[2].parse().unwrap();
Is there a simpler way?
You can use
scan-rules
for this:If you want to do something a little more involved, you can use multiple rules and type inference, and specify what to do if the input doesn't match any of the rules given (by default it
panic!
s):Disclaimer: I am the author of
scan-rules
.I am new to Rust so I may not have all this down exactly but I have made a solution. I discovered you can use split_white_space to put the integers in the string into an iterator. Then you unwrap it out of std::option::Option<&str> using ".unwrap()". After parse the &str using ".parse()" and unwrap its result using ".unwrap()". Then you have an int if you have specified the type of variable using "variable_name: i32 =...". Checkout what I did:
You can use
text_io
for this:text_io
0.1.3
also supports ascan!
macro:in case you want to read from a file or some other source, you can also use both macros on any type that implements
Iterator<Item=u8>
:or
You can leave off the
: i32
s if the compiler can infer those types from context.Disclaimer: I am the author of
text_io
.