PrevNext

Input & Output

Authors: Darren Yao, Benjamin Qi, Allen Li

Demonstrates how to read input and print output for USACO contests, including an example problem.

Edit This Page

C++

Resources
IUSACO

module is based off this

CPH

cin, getline, files

PAPS

cin, getline

Java

Resources
IUSACO

module is based off this

Python

The code snippets below will read in three integers as part of a single line and output their sum. For example, given the input

1 2 3

the output will be as follows:

The sum of these three numbers is 6

Feel free to test them out at ide.thecodingwizard.me.

Out of the methods below, which one should I use?

It doesn't matter. Whichever you're most comfortable with!

Standard I/O

In most websites (such as CodeForces and CSES), and in USACO problems after December 2020, input and output are standard.

C++

Method 1 - <iostream>

More straightforward to use. Calling the extraction operator operator>> on cin reads whitespace-separated data from standard input. Similarly, calling the insertion operator operator<< on cout writes to standard output. The escape sequence \n represents a new line.

#include <iostream>
using namespace std;
int main() {
int a;
int b;
int c;
cin >> a >> b >> c;
// "\n" can be replaced with endl as well
cout << "The sum of these three numbers is " << a + b + c << "\n";
}

endl vs \n

endl and \n are not equivalent; see Fast I/O for details.

Method 2 - <cstdio>

This library includes the scanf and printf functions, which are slightly more complicated to use.

#include <cstdio>
using namespace std;
int main() {
int a;
int b;
int c;
/*
* %d specifies that a value of type int is being input.
* To input a 64-bit (long long) number,

Input Speed

The second method is significantly faster (generally only an issue with large input sizes). However, the first method can be sped up so that the difference in speed is not significant; see Fast I/O for details.

Java

Method 1 - Scanner and System.out.print

In your CS classes, you've probably implemented input and output using standard input and standard output, or using Scanner to read input and System.out.print to print output.

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
System.out.print("The sum of these three numbers is ");
System.out.println(a + b + c);
}
}

This works, but Scanner and System.out.print are slow when we have to handle inputting and outputting tens of thousands of lines.

Method 2 - BufferedReader and PrintWriter

These are faster because they buffer the input and output and handle it all at once as opposed to parsing each line individually. However, BufferedReader is harder to use than Scanner. It has quite a few more methods and the io library must be imported for its use as well. A StringTokenizer is used to split the input line by whitespace into tokens, which are then accessed individually by the nextToken() method.

import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
StringTokenizer st = new StringTokenizer(r.readLine());
int a = Integer.parseInt(st.nextToken());

I/O Template

The following template (a shortened version of Kattis's Kattio.java) combines BufferedReader and PrintWriter and takes care of the string processing for you.

import java.io.*;
import java.util.*;
/**
* Simple yet moderately fast I/O routines.
* Some notes:
*
* - When done, you should always do io.close() or io.flush() on the
* Kattio-instance, otherwise, you may lose output.
*

Optional: extends

extends is used so that Kattio inherits methods from PrintWriter (including print(), println() and close()). If you're interested, see here for more details.

The input methods in our Kattio class mimic those of Scanner. Given an instance io:

MethodDescription
io.next()Reads the next token (up to a whitespace) and returns a String
io.nextInt()Reads the next token (up to a whitespace) and returns as an int
io.nextLong()Reads the next token (up to a whitespace) and returns as a long
io.nextDouble()Reads the next token (up to a whitespace) and returns as a double
io.print(arg)Prints arg to designated output stream
io.println(arg)Prints arg to designated output stream and adds a newline
io.close()Closes the output stream and flushes the output. Make sure to call this (or io.flush()) at the end, or you won't see any output!

USACO prohibits prewritten code but allows you to consult resources about basic functionality such as input / output, so feel free to refer to this module during a USACO contest.

PrintWriter Buffering

The original Kattio code had super(new BufferedOutputStream(o)); on line 37. But since PrintWriter uses buffered output, including BufferedOutputStream is necessary.

Similarly, you may see PrintWriters for file output initialized like the following (ex. here).

PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("problemname.out")));

but

PrintWriter pw = new PrintWriter(new FileWriter("problemname.out"));

suffices.

Input Speed

See Fast I/O for a comparison of input speeds as well as a faster method of input.

Python

Method 1 - input() and print()

The most intuitive way to do input/output is using the built in input() and print() methods. The input() method will return the next line, and can be processed using various Python methods. The print() method takes in a string and an optional string end (defaults to '\n'). Below is an annotated demonstration on different input/output scenarios.

# Read in a string
my_str = input()
# Prints the string on its own line
print(my_str)
# Take in an integer n on a single line
n = int(input())
# Prints n with " test" (no newline) after it
print(n, end=" test")

Method 2 - stdin and stdout

The first method of reading input can be far slower (sometimes hundreds of times slower!) than using stdin. Coupled with Python's relatively slow execution speed, reading input quickly becomes incredibly important.

# Import the sys module to use stdin/stdout
import sys
# sys.stdin/stdout is similar to a file in that we read lines for input/output
my_str = sys.stdin.readline()
sys.stdout.write(str(myStr) + '\n')
# Renaming the read/write methods for convenience
input = sys.stdin.readline
print = sys.stdout.write

We can also use split, map or a list comprehension to read in multiple whitespace-separated integers on the same line.

import sys
# Read in a series of numbers on one line into a list
nums = [int(x) for x in input().split()]
# This does the same thing
nums = list(map(int, input().split()))
# stdin/stdout, just replace input() with sys.stdin.readline()
nums = list(map(int, sys.stdin.readline().split()))

We can use something similar to the above if we are unpacking a fixed number of integers.

import sys
# Read in integers n and m on the same line with a list comprehension
n, m = [int(x) for x in input().split()]
# Do the same thing but with map instead
n, m = map(int, input().split())
# stdin and stdout
n, m = map(int, sys.stdin.readline().split())

So taking three integers as input and printing their sum is quite simple. On a larger scale (thousands of integers), using stdin and stdout becomes far more important for speed:

import sys
a, b, c = map(int, input().split())
print("The sum of these three numbers is", a + b + c)
# stdin and stdout
a, b, c = map(int, sys.stdin.readline().split())
print("The sum of these three numbers is", a + b + c)

Example Problem - Weird Algorithm

Focus Problem – read through this problem before continuing!

Try to implement this yourself!

Resources
GCP

example C++ solution for this problem

C++

As noted in the resource above, this problem requires 64-bit integers.

Solution

Java

As noted in the resource above, this problem requires 64-bit integers.

Method 1 - Scanner and System.out.print

Method 1

Method 2 - BufferedReader and PrintWriter

Method 2

With Kattio

Kattio

Python

Solution

File I/O

Update

USACO problems from December 2020 onwards use standard I/O rather than file I/O. You'll still need to use file I/O to submit to earlier problems.

In older USACO problems, the input and output file names are given and follow the convention problemname.in. After the program is run, output must be printed to a file called problemname.out.

Focus Problem – read through this problem before continuing!

You must use the correct file names when opening the .in and .out files, depending on the problem. The file names are given on USACO problems which require file opening. For example, you would open paint.in and paint.out in the above problem.

C++

Method 1 - freopen

You will need the <cstdio> library. The freopen statements reuse standard I/O for file I/O. Afterwards, you can simply use cin and cout (or scanf and printf) to read and write data.

#include <iostream>
#include <cstdio>
using namespace std;
int main() {
freopen("problemname.in", "r", stdin);
// the following line creates/overwrites the output file
freopen("problemname.out", "w", stdout);
// cin now reads from the input file instead of standard input

To test your solution locally without file I/O, just comment out the lines with freopen.

For convenience, we can define a function that will redirect stdin and stdout based on the problem name:

#include <iostream>
#include <cstdio>
using namespace std;
// the argument is the input filename without the extension
void setIO(string s) {
freopen((s + ".in").c_str(), "r", stdin);
freopen((s + ".out").c_str(), "w", stdout);
}

Method 2 - <fstream>

You cannot use C-style I/O (scanf, printf) with this method.

#include <fstream>
using namespace std;
int main() {
ifstream fin("problemname.in");
ofstream fout("problemname.out");
int a;
int b;
int c;
fin >> a >> b >> c;
fout << "The sum of these three numbers is " << a + b + c << "\n";
}

Java

Java

Again, BufferedReader and PrintWriter should be used. Note how static initialization of r and pw is slightly different.

import java.io.*;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader r = new BufferedReader(new FileReader("problemname.in"));
PrintWriter pw = new PrintWriter("problemname.out");
StringTokenizer st = new StringTokenizer(r.readLine());
int a = Integer.parseInt(st.nextToken());

With Kattio

import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Kattio io = new Kattio("problemname");
int a = io.nextInt();
int b = io.nextInt();
int c = io.nextInt();
io.print("The sum of these three numbers is ");

Python

Python

See here for documentation about file I/O.

The most intuitive way to do file I/O in Python is by redirecting the system input and output to files. After doing this, you can then use the above input() and print() methods as usual.

import sys
sys.stdin = open("problemname.in", "r")
sys.stdout = open("problemname.out", "w")

A different approach to file I/O in Python is to still use the open() method, but use the built-in functions .readline() or .readlines():

"""
Note: The second argument can be omitted in the open()
command for read-only files
"""
fin = open("problemname.in", "r")
fout = open("problemname.out", "w")
# One way to read the file using .readline()
line1 = fin.readline()
# readline() will pick up where you left off
  • fin.readline() will return the next line as a string. This method is useful for problems where you only have to read a short amount of lines but you still need to map each value to a variable.

  • fin.readlines() returns all of the file's content as a list, separated by newlines ("\n"). Combined with a for loop, this method provides a concise way to separate variables in the same line in a problem. Keep in mind that each line entry in the list will still have a "\n" at the end.

  • fout.write(data) will write the variable data to the file. data must be a string, and you can convert non-string variables with str(my_var). The write() method will NOT write a new line at the end. You must also run fout.write("\n") if you wish to write a new line.

  • f-strings were added in Python 3.6, and generally look nicer than concatenating (adding) strings. To define an f-string, simply add the letter f right before the start of the string, and any variables or expressions enclosed in curly braces ({}) will be put into the string. As an example, fout.write(f"{var1} {var2} {var3+var4}") looks much cleaner than fout.write(str(var1)+" "+str(var2)+" "+str(var3+var4))

After you read a line, you may wish to process it further. Python has many built-in string methods and functions:

  • str.strip() removes any trailing or leading whitespace. You should always run this method after reading a line, to ensure that there is no extra whitespace: line = fin.readline().strip()

  • map(func, iterable) will run a function (the func argument) against each element of an iterable (list) you pass it. This is useful for changing a list of strings into a list of ints: nums = list(map(int, ["1", "2", "3"])). Please note that map() returns a Map object, and you need to convert it into a list with list().

  • str.split(delim) will split the string. If no argument is passed, it will split by space. This is useful if you want to separate a string of space-separated integers into ints: nums = list(map(int, line.split()))

Example Solution - Fence Painting

Resources
USACO

Make sure to read this.


For an explanation of the solutions below, check the Rectangle Geometry module.

C++

Method 1 - freopen

Method 1

Method 2 - <fstream>

Method 2

Java

Method 1 - Scanner and PrintWriter

Method 1

Method 2 - BufferedReader and PrintWriter

Method 2

With Kattio

Kattio

Python

Method 1

Method 1

Method 2

Redirecting file input using sys, as mentioned above.

Method 2

USACO Note - Extra Whitespace

Importantly, USACO will automatically add a newline to the end of your file if it does not end with one.

Warning!

Occasionally, there is a period of time near the beginning of the contest window where the model outputs do not end in newlines. This renders the problem unsolvable.

Make sure not to output trailing spaces, or you will get an error such as the following:

bad

Here are some examples of what is allowed and what isn't when the intended output consists of a single integer ans:

C++

C++

cout << ans; // OK, no newline
cout << ans << endl; // OK, newline
cout << ans << "\n"; // OK, newline
cout << ans << " "; // NOT OK, extra space
cout << ans << "\n\n"; // NOT OK, extra newline

Java

Java

pw.print(ans); // OK, no newline
pw.println(ans); // OK, newline
pw.print(ans + "\n"); // OK, newline
pw.print(ans + " "); // NOT OK, extra space
pw.print(ans + "\n\n"); // NOT OK, extra newline

Python

Python

print(ans, end='') # OK, no newline
print(ans) # OK, newline
print(str(ans) + '\n', end='') # OK, newline
print(str(ans) + " ", end='') # NOT OK, extra space
print(str(ans) + '\n') # NOT OK, extra newline

Module Progress:

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!

PrevNext