STDINを取得したい
競技プログラミングでよくある入力はUNIXで言うところの標準入力に値が入っている状態だ。なのでSTDINから値を取り出したい。
- パイプだとこんな感じのイメージ
$ echo "input-text" | ruby main.rb
STDIN.raw
でやってみる
- ドキュメントを見るとこれでよさそうなのだが、
#raw
メソッドがターミナル(tty)を開いてないと動かない仕様なのでダメ-
can't set IO#raw: Inappropriate ioctl for device
のようなエラーが出る -
io/console.cr#L79 曰く
Only call this when this IO is a TTY, such as a not redirected stdin.
- テスト結果 crystal 0.22.0 on wandbox
-
begin
array = STDIN.raw.each_line.map{|line| line.dup}
puts array.class
array.each_with_index{|line, index| puts "#{line} <- #{index}"}
#p array.size
rescue ex
puts ex.message
end
- 出力
Start
Using compiled compiler at .build/crystal
can't set IO#raw: Inappropriate ioctl for device
0
Finish
STDIN
直で
- STDINを直でとるとうまくいった
begin
array = STDIN.each_line.map{|line| line.dup}
puts array.class
array.each_with_index{|line, index| puts "#{line} <- #{index}"}
#p array.size
rescue ex
puts ex.message
end
- 出力
Start
Using compiled compiler at .build/crystal
Iterator::Map(IO::LineIterator(IO::FileDescriptor, Tuple(), NamedTuple()), String, String)
aaa <- 0
hello <- 1
world <- 2
0
Finish
もう少し短く
- crystalのmapの省略記法は
:
ではなく.
array = STDIN.each_line.map(&.to_s)
- 自動で配列になってくれないので、
to_a
をつける
array = STDIN.each_line.map(&.to_s).to_a