LoginSignup
3
3

More than 5 years have passed since last update.

競技プログラミング等における標準入力からの値の入出力方法

Last updated at Posted at 2017-03-17

よく忘れてしまうので調べたらメモする。

1行に1つの整数

5

R

R
n <- scan("stdin", quiet = TRUE) # 入力
cat(n) # 出力

quiet=TRUEを指定しないと読み込み時に"Read 1 item"と出力され、これがエラーメッセージと判断される場合がある。

Python2

Python2
n = input() # 入力
print n     # 出力

Python3

Python3
n = int(input()) # 入力
print(n)         # 出力

Ruby

Ruby
n = gets.to_i # 入力
puts n        # 出力

C++

C++
#include <iostream>
int main(void){
    int n;
    std::cin >> n; // 入力
    std::cout << n << std::endl; // 出力

    return 0;
}

iostreamでは遅いといった場合はcstdioを使用したほうが良い模様。

1行に複数の整数

1 2 3

Python3

python3
n = [int(i) for i in input().split()] # 入力
print(' '.join([str(i) for i in n]))  # 出力
python3
a, b, c = [int(i) for i in input().split()] # 入力
print(a, b, c)  # 出力
python3
n = list(map(int, input().split()) # 入力
print(' '.join(map(str, n))) # 出力

Ruby

Ruby
n = gets.chomp.split.map { |i| i.to_i } # 入力
puts n.join(' ') # 出力
Ruby
a, b, c = gets.chomp.split.map { |i| i.to_i } # 入力
puts "#{a} #{b} #{c}" # 出力
3
3
2

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
3