4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rustで標準入力を取得する

Last updated at Posted at 2023-01-10

プログラミングの問題を解くときに使用している標準入力の取得方法まとめ

Stringで取得

use std::io;

fn read_buffer() -> String {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).expect("Failed to read line.");
    buffer.trim().to_string()
}

符号なし整数で取得

use std::io;

fn read_buffer() -> u32 {
    let mut buffer = String::new();
    match io::stdin().read_line(&mut buffer) {
        Ok(_) => buffer.trim().parse().expect("Failed to parse."),
        Err(e) => panic!("Failed to read line: {}", e)
    }
}

ベクタ型(String)

スペース区切りで入力された場合

use std::io;

fn read_buffer() -> Vec<String> {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).expect("Failed to read line.");
    buffer.trim().split_whitespace().map(|s| s.to_string()).collect()
}

ベクタ型(符号なし整数)

スペース区切りで入力された場合

use std::io;

fn read_buffer() -> Vec<u32> {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).expect("Failed to read line.");
    buffer.trim()
        .split_whitespace()
        .map(|s| s.parse().expect("Failed to parse."))
        .collect()
}

ベクタ型(char)

スペース区切りで入力された場合

use std::io;

fn read_buffer() -> Vec<char> {
    let mut buffer = String::new();
    io::stdin().read_line(&mut buffer).expect("Failed to read line.");
    buffer.trim().chars().collect()
}
4
4
1

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
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?