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.

Focus Problem – read through this problem before continuing!

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

Whichever you're most comfortable with!

C++

Method 1: <iostream>

1#include <iostream>
2using namespace std;
3
4int main() {
5 int x; cin >> x;
6 cout << "FOUND " << x << "\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 x, y;
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.

Here is a Java template for input and output, which is effectively a faster Scanner. We import the entire util and io libraries for ease of use. Note that this must be declared within a file with the same name as the public class (so template.java) in this case.

1import java.io.*;
2import java.util.*;
3
4public class template {
5 static class InputReader {
6 BufferedReader reader;
7 StringTokenizer tokenizer;
8 public InputReader(InputStream stream) {
9 reader = new BufferedReader(new InputStreamReader(stream), 32768);
10 tokenizer = null;

Here's a brief description of the methods in our InputReader class, with an instance r, and PrintWriter with an instance pw.

MethodDescription
r.next()Reads the next token (up to a whitespace) and returns a String
r.nextInt()Reads the next token (up to a whitespace) and returns as an int
r.nextLong()Reads the next token (up to a whitespace) and returns as a long
r.nextDouble()Reads the next token (up to a whitespace) and returns as a double
pw.println()Prints the argument to designated output stream and adds a newline
pw.print()Prints the argument to designated output stream

Here's an example to show how input/output works. Let's say we want to write a program that takes three numbers as input and prints their sum.

1// InputReader template code above
2static InputReader r = new InputReader(System.in);
3static PrintWriter pw = new PrintWriter(System.out);
4
5public static void main(String[] args) {
6 int a = r.nextInt();
7 int b = r.nextInt();
8 int c = r.nextInt()
9 pw.println(a + b + c);
10 pw.close();

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

This section is not complete.

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

redirect to some other source which covers this?

Example Solution - Weird Algorithm

Resources
GCPexample solution for this problem

Try to implement this yourself!

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.

With Scanner

With InputReader / PrintWriter

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

We can slightly modify the template above to support file I/O. Note how r and pw must be initialized in a different way.

1import java.util.*;
2import java.io.*;
3
4public class template {
5 static class InputReader {
6 BufferedReader reader;
7 StringTokenizer tokenizer;
8 public InputReader() throws FileNotFoundException {
9 reader = new BufferedReader(new FileReader("problemname.in"));
10 tokenizer = null;

Some sources say to use

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

on line 28. There is no need to add BufferedWriter since PrintWriter uses buffered output.

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

Example Solution - Fence Painting

Resources
USACOMake sure to read this.

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

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.

1#include <iostream>
2#include <vector>
3using namespace std;
4
5int main() {
6 freopen("paint.in","r",stdin);
7 // reuse standard in to read from "paint.in"
8 freopen("paint.out","w",stdout);
9 // reuse standard out to write to "paint.out"
10 vector<bool> cover(100);

Method 2

Use ifstream & ofstream.

1#include <fstream>
2#include <vector>
3using namespace std;
4
5int main() {
6 ifstream fin("paint.in");
7 ofstream fout("paint.out");
8 vector<bool> cover(100);
9 int a, b, c, d; fin >> a >> b >> c >> d;
10 for (int i = a; i < b; ++i) cover[i] = 1;

Java

Method 1 - Scanner

1import java.util.*;
2import java.io.*;
3
4public class template {
5 public static void main(String[] args) throws FileNotFoundException, IOException {
6 Scanner r = new Scanner(new File("paint.in"));
7 PrintWriter pw = new PrintWriter(new FileWriter("paint.out"));
8
9 int a = r.nextInt(), b = r.nextInt();
10 int c = r.nextInt(), d = r.nextInt();

Method 2 - BufferedReader

1import java.io.*;
2import java.util.*;
3
4public class paintSol { // must be declared in paintSol.java
5 public static void main(String[] args) throws IOException {
6 BufferedReader br = new BufferedReader(new FileReader("paint.in"));
7 PrintWriter pw = new PrintWriter(new FileWriter("paint.out"));
8 int[] cover = new int[100];
9
10 StringTokenizer st = new StringTokenizer(br.readLine());

Method 3 - InputReader

Alternatively, we can use the InputReader given above. Note how this is almost identical to the code using Scanner.

1import java.util.*;
2import java.io.*;
3
4public class template {
5 static class InputReader {
6 BufferedReader reader;
7 StringTokenizer tokenizer;
8 public InputReader() throws FileNotFoundException {
9 reader = new BufferedReader(new FileReader("paint.in"));
10 tokenizer = null;

Python

Redirecting file input using sys,

1import sys
2
3sys.stdin = open("paint.in", "r")
4sys.stdout = open("paint.out", "w")
5cover = [0] * 100
6a, b = map(int, input().split())
7c, d = map(int, input().split())
8for i in range(a, b):
9 cover[i] = 1
10for i in range(c, d):

Alternatively,

1with open('paint.in','r') as inp:
2 cover = [0] * 100
3 lines = [line for line in inp]
4 a, b = map(int,lines[0].split())
5 c, d = map(int,lines[1].split())
6 for i in range(a, b):
7 cover[i] = 1
8 for i in range(c, d):
9 cover[i] = 1
10 ans = 0

Module Progress:

Give Us Feedback on Input & Output!

PrevNext