LoginSignup
3
2

More than 1 year has passed since last update.

競プロのローカルテストで標準出力だけ出したい

Last updated at Posted at 2022-07-25

結論

 Linux 系は cat input.txt | ./a.out ./a.out < input.txt

 Windows は、

  • PowerShell なら cat input.txt | .\a.out
  • cmd なら .\a.out < input.txt(追記:type input.txt | .\a.out でも可)

 なお、PowerShell で小規模な入力なら Get-Clipboard | .\a.out が便利

本文

 競プロの問題をローカルテストする時、手元にコードを書いて、コピペで入出力を検証する人は多いと思います。単純な問題なら特に問題ないですが、複数の数値を入力しながら出力をしていく形式、特にテストケースが多数ある問題だと、入力と出力の値が入り混じって、出力の検証がしづらいという問題があります。

 また、この他に根本的な問題として、大規模な入力だとそもそもクリップボードに貼り付けることができません。

 以上のような場合、別にテキストファイルを用意して、それを実行ファイルに読ませる必要があります。

具体的には

 Codeforcesのこの問題を例にすると、

example input
5
5009
7
9876
10000
10
example output
2
5000 9
1
7 
4
800 70 6 9000 
1
10000 
1
10

 これをコピペで検証すると、

local console
PS C:\Users\user> .\a.exe
5
5009
2
9 5000
7
1
7
9876
4
6 70 800 9000
10000
1
10000
10
1
10

 となって、かなり検証しづらいです。

対策

 例えば C++ の場合、fstream を用いてテキストファイルを読み込ませる方法がありますが、いちいちコードを差し替える必要があるので手間になります。

 そこで、ここではコマンドライン上で直接テキストファイルを参照する方法を紹介します。OS やコンソールによって多少方言の違いがあるので注意です。

Linux 系

 catコマンドとパイプを使うことにより実行できます。

local console
user@DESKTOP-XXXXXXX:/mnt/c/Users/user$ cat input.txt | ./a.exe
2
9 5000
1
7
4
6 70 800 9000
1
10000
1
10

 また、リダイレクトにより同様のことができます。

local console
user@DESKTOP-XXXXXXX:/mnt/c/Users/user$ ./a.exe < input.txt
2
9 5000
1
7
4
6 70 800 9000
1
10000
1
10

 なお、上記の実行結果は WSL 上で再現を行っています。Linux のネイティブ環境や Mac OS ではもしかして挙動が違う場合もあるかもしれませんが、あしからず。

Windows

 コマンドプロンプトではリダイレクトが使えます。

local console
C:\Users\user>.\a.exe < input.txt
2
9 5000
1
7
4
6 70 800 9000
1
10000
1
10

 cat は使えません。(追記:type というコマンドで同様のことができるようです)

local consle
C:\Users\user>cat input.txt | .\a.exe
'cat' は、内部コマンドまたは外部コマンド、
操作可能なプログラムまたはバッチ ファイルとして認識されていません。

 PowerShell では cat が使えます。

local console
PS C:\Users\user> cat .\input.txt | .\a.exe
2
9 5000
1
7
4
6 70 800 9000
1
10000
1
10

 逆に、リダイレクトが使えません。

local_console
PS C:\Users\user> .\a.exe < input.txt
発生場所 行:1 文字:9
+ .\a.exe < input.txt
+         ~
演算子 '<' は、今後の使用のために予約されています。
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : RedirectionNotSupported

便利な Get Clipboard(PowerShell)

 ほとんどの場合、ローカルテストはクリップボードに収まる範囲の入力を検証することが多いです。

 PowerShell の場合、クリップボードの内容を直接入力にして出力だけを表示させることが可能です。

local_console
PS C:\Users\user> Get-Clipboard | .\a.exe  
2
9 5000
1
7
4
6 70 800 9000
1
10000
1
10

 わざわざ別に input.txt を用意する必要がないので、かなり便利です。

 

3
2
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
3
2