[RUBY] Input / output method of values from standard input in competitive programming, etc.

I often forget it, so I'll write it down when I look it up.

One integer per line

5

R

R


n <- scan("stdin", quiet = TRUE) #input
cat(n) #output

If quiet = TRUE is not specified, "Read 1 item" will be output when reading, which may be judged as an error message.

Python2

Python2


n = input() #input
print n     #output

Python3

Python3


n = int(input()) #input
print(n)         #output

Ruby

Ruby


n = gets.to_i #input
puts n        #output

C++

C++


#include <iostream>
int main(void){
    int n;
    std::cin >> n; //input
    std::cout << n << std::endl; //output

    return 0;
}

It seems that it is better to use cstdio when iostream is slow.

Multiple integers on one line

1 2 3

Python3

python3


n = [int(i) for i in input().split()] #input
print(' '.join([str(i) for i in n]))  #output

python3


a, b, c = [int(i) for i in input().split()] #input
print(a, b, c)  #output

python3


n = list(map(int, input().split()) #input
print(' '.join(map(str, n))) #output

Ruby

Ruby


n = gets.chomp.split.map { |i| i.to_i } #input
puts n.join(' ') #output

Ruby


a, b, c = gets.chomp.split.map { |i| i.to_i } #input
puts "#{a} #{b} #{c}" #output

Recommended Posts

Input / output method of values from standard input in competitive programming, etc.
Python3 standard input for competitive programming
Notes on standard input / output of Go
Standard input / output summary
[For beginners of competitive pros] Three input methods to remember when starting competitive programming in Python
Find the average / standard deviation of the brightness values in the image
Coordination of each process in MPI and buffering of standard output
Write standard input in code
Part 1 of receiving standard input
Story of trying competitive programming 2
Re: Competitive Programming Life Starting from Zero Chapter 1.2 "Python of Tears"
Make standard output non-blocking in Python
Story of trying competitive programming Part 1
Tips (input / output) that you should know when programming competitive programming with Python2
Trends in programming languages from the perspective of GitHub (updated semi-annual changes)
Even in the process of converting from CSV to space delimiter, seriously try to separate input / output and rules