111
101

More than 5 years have passed since last update.

Paizaで使える標準入力の取得

Last updated at Posted at 2016-08-05

PaizaではDランク〜Sランクまでのプログラミング問題が解けます。対応言語もPHP、Javascript、Python、Swiftなど多いので自分の得意な言語で挑戦できます。私はPHPで問題を解いていますが、単一行や複数行で渡される標準入力を取得するコードを毎回書くのがめんどくさいのでコピペ用にメモしておきます。

標準入力が一行の場合

<?php

// 標準入力からの入力値を変数に代入します
$single_line_input = fgets(STDIN);
// 取得した入力値を半角スペースで分解します
$array = explode(" ", $input_line);
// 単一行の入力の場合はこれだけで各入力値が配列の要素として使えます

Paizaでは自分の環境でテストを行うことが推奨されているようです。テスト時にstdin.txtというファイルから入力を得るとすると次のようになると思います。

<?php

// ファイルパスの指定
$file = fopen(".../path/to/stdin.txt", "r");
// ファイル内容の読み込み
$single_line_input_line = fgets($file);
// 入力値の分解
$array = explode(" ", $input_line);
// ファイルパスを閉じる
fclose($file);

標準入力が複数行の場合

1行ずつ代入するっていうのがちょっとめんどくさいですね。

<?php

// 標準入力を一行ずつ配列に代入します
while ($line = fgets(STDIN)) {
   $tmp[] = trim($line);
}

// 配列の各要素をさらに分解します
foreach ($tmp as $key => $value) {
  $array[] = explode(" ", $value);
}

自分の環境でテストする場合

<?php

// ファイルパスの指定
$file = fopen(".../path/to/stdin.txt", "r");

// ファイルの内容を一行ずつ配列に代入します
if($file) {
  while ($line = fgets($file)) {
    $tmp[] = trim($line);
  }
}

// 配列の各要素をさらに分解します
foreach ($tmp as $key => $value) {
  $array[] = explode(" ", $value);
}

// ファイルパスを閉じる
fclose($file);
111
101
4

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
111
101