23
19

More than 1 year has passed since last update.

[Rustで簡単標準入力]proconio使い方まとめ

Posted at

proconioとは

Rustでの標準入力を簡単にしてくれるマクロです。
Atcoderでも使えるので、愛用させてもらってます。
自分が使い方を忘れるのでまとめて記事にしました。

導入

cargo.tomldependenciesに追記する

Cargo.toml
[dependencies]
proconio = "0.4.3"

サンプル

入力
hoge 3.0 8 
use proconio::input;

fn main() {
     input! {
        n: String,
        m: f32,
        l: i32,
    }
    println!("{} {} {}", n, m, l);
}
出力
hoge 3.0 8

ポイント

use proconio::input;で使用を宣言

input!{}がproconioの機能

変数名:型,が基本形

mutableで受け取る

抜粋
input! {
   a: f32,
   mut b: i32,
}
b += a;

前にmutを付ければOK!

配列

n個の1次元配列を受け取る

入力
4
1 2 6 8
抜粋
input! {
        n: u8,
        a:[i32;n],
    }

    println!("{:?}", a);
出力
1 2 6 8

n * mの2次元配列を受け取る

入力
3
3
5 2 1
6 2 8
2 5 2
抜粋
input! {
        n: u8,
        m: u8,
        a: [[i32; m]; n],
    }

    println!("{:?}", a);
出力
5 2 1
6 2 8
2 5 2

a: [[5, 2, 1], [6, 2, 8], [2, 5, 2]]となる。

文字列をVec<char>で受け取る

入力
qiita
use proconio::input;
use proconio::marker::Chars;

fn main() {
    input! {
        s: Chars,
    }
    println!("{:?}", s)
}
出力
['q', 'i', 'i', 't', 'a']

use proconio::marker::Chars;を追記する。

変数名 : Chars,で使用する。

文字列を入れ替える問題等、様々な場面で使える便利機能。

注意点

宣言した入力形式と、実際の入力形式が違うとエラーとなる。

i32で宣言したのに文字列をブチ込んだ例
thread 'main' panicked at 'failed to parse the input `h` to the value of type `i32`: ParseIntError

参考URL (超感謝(m(__)m)

便利なのでぜひ使ってみてください!

23
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
19