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.

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>

1#include <iostream>
2using namespace std;
3
4int main() {
5 int a, b, c; cin >> a >> b >> c;
6 cout << "sum is " << a+b+c << "\n";
7}

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

1#include <cstdio>
2using namespace std;
3
4int main() {
5 int a, b, c;
6 // %d specifies that a value of type int is being input.
7 // Use %lld (a few judging platforms might need %I64d)
8 // to input a long long (64-bit) integer.
9 // Many other specifiers are also available; see link for more details.
10 // 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.

1/** Simple yet moderately fast I/O routines.
2 *
3 * Example usage:
4 *
5 * Kattio io = new Kattio();
6 *
7 * while (io.hasMoreTokens()) {
8 * int n = io.nextInt();
9 * double d = io.nextDouble();
10 * 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).

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

but

1PrintWriter 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.

1# read in a string
2myStr = input()
3# prints the string on its own line
4print(myStr)
5
6# take in an integer n on a single line
7n = int(input())
8# prints integer n with " test" after it
9print(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).

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

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

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

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

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

This section is not complete.

Feel free to file a request to complete this using the "Contact Us" button.

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.

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

Method 2: <fstream>

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

1#include <fstream>
2using namespace std;
3
4int main() {
5 ifstream fin("problemname.in");
6 ofstream fout("problemname.out");
7 // rest of your code ...
8
9}

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.

1import sys
2
3sys.stdin = open("problemname.in", "r")
4sys.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:

1cout << ans; // OK, no newline
2cout << ans << endl; // OK, newline
3cout << ans << "\n"; // OK, newline
4cout << ans << " "; // NOT OK, extra space
5cout << ans << "\n\n"; // NOT OK, extra newline

Python

Python

For method 2:

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

PrevNext