PrevNext

Input & Output

Authors: Darren Yao, Benjamin Qi, Nathan Wang, Allen Li

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

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.

C++

Resources
IUSACOmodule is based off this
CPHcin, getline, files
PAPScin, getline

Java

Resources
IUSACOmodule is based off this

Python

Standard I/O

In most websites (such as CodeForces and CSES), input and output are standard. Here, we'll provide examples that take three integers as input and prints their sum. Feel free to test these 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!

C++

Method 1: <iostream>

#include <iostream>
using namespace std;
int main() {
int a, b, c; cin >> a >> b >> c;
cout << "sum is " << a+b+c << "\n";
}

Method 2: <cstdio>

This library includes the scanf and printf functions, which are slightly more complicated to use, but are significantly faster (generally only an issue with large input sizes):

#include <cstdio>
using namespace std;
int main() {
int a, b, c;
// %d specifies that a value of type int is being input.
// Use %lld (a few judging platforms might need %I64d)
// to input a long long (64-bit) integer.
// Many other specifiers are also available; see link for more details.
// Be sure to add a & character (address-of operator) when using

The first method can be sped up so that the difference in speed is not significant; see Fast I/O for details.

Java

Java

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. These methods work, but Scanner and System.out.print are slow when we have to handle inputting and outputting tens of thousands of lines. Thus, we use BufferedReader and PrintWriter instead, which 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.

Here is a Java template for input and output that which combines BufferedReader and PrintWriter, based off Kattis's Kattio.java. Note that we import the entire util and io libraries for ease of use.

/** Simple yet moderately fast I/O routines.
*
* Example usage:
*
* Kattio io = new Kattio();
*
* while (io.hasMoreTokens()) {
* int n = io.nextInt();
* double d = io.nextDouble();
* double ans = d*n;

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.println()Prints the argument to designated output stream and adds a newline
io.print()Prints the argument to designated output stream
io.close()Closes the output stream and flushes the output

Warning!

If you don't call io.close() at the end or io.flush(), you won't see any output!

PrintWriter Buffering

The original Kattio code had super(new BufferedOutputStream(o)); on line 37. But since PrintWriter uses buffered output, I don't think 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"));

should suffice.

Python

Python

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 different 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
myStr = input()
# prints the string on its own line
print(myStr)
# take in an integer n on a single line
n = int(input())
# prints integer n with " test" after it
print(n, end=" test")

We can also split along with map or a list comprehension to read in multiple integers on the same line (separated by whitespace).

# read in a series of numbers on one line into a list
nums = [int(x) for x in input().split()]
# does the same thing
nums = list(map(int, input().split()))

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

# read in integers n and m, both on the same line
n, m = [int(x) for x in input().split()]
# does the same thing
n, m = map(int, input().split())

So taking three integers as input and printing their sum is quite simple:

a,b,c = map(int, input().split())
print("sum is",a+b+c)

This section is not complete.

Any help would be appreciated! Just submit a Pull Request on Github.

is there some other source which covers this?

Example Problem - Weird Algorithm

Focus Problem – read through this problem before continuing!

Try to implement this yourself!

Resources
GCPexample 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

Method 3 - Kattio

Essentially the same as method 2.

Method 3

Python

Solution

File I/O

Focus Problem – read through this problem before continuing!

In USACO, input is read from a file called problemname.in. After the program is run, output must be printed to a file called problemname.out. Note that you'll have to rename the .in and .out files depending on the problem. For example, in the above problem you would use paint.in and paint.out.

C++

Method 1: freopen

You will need the <cstdio> library.

#include <cstdio>
using namespace std;
int main() {
freopen("problemname.in", "r", stdin);
freopen("problemname.out", "w", stdout);
// rest of your code ...
// can use cin or scanf
}

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");
// rest of your code ...
}

Java

Java

Again, BufferedReader and PrintWriter should be used. The provided constructor public Kattio(String problemName) handles file input / output for you.

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")

Warning: USACO Note

Since USACO currently uses python 3.4.0, f-strings are not supported (they will result in a missing output file).

Example Solution - Fence Painting

Resources
USACOMake sure to read this.

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

C++

Method 1

Use freopen. If you comment out both of the lines containing freopen then the program reads from standard in and writes to standard out as usual.

Method 1

Method 2

Use ifstream & ofstream.

Method 2

Java

Method 1 - Scanner and PrintWriter

Method 1

Method 2 - BufferedReader and PrintWriter

Method 2

Method 3 - Kattio

Essentially the same as method 2. Note how static initialization of io is different compared to standard input / output since we need to catch IOExceptions.

Method 3

Python

Method 1

Method 1

Method 2

Redirecting file input using sys, as mentioned above.

Method 2

Note - Extra Whitespace

Importantly, USACO will automatically add a newline to the end of your file if it does not end with one. 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:

C++

C++

For method 1:

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

Python

Python

For method 2:

print(ans) # OK, newline
print(ans,end='') # OK, no newline
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!

Give Us Feedback on Input & Output!

Leave suggestions for us by making a post on the USACO Forum! Ex: Unclear sections, mislabeled problems, etc.

PrevNext