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.

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

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>

#include <iostream>
using namespace std;
int main() {
int x; cin >> x;
cout << "FOUND " << x << "\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 x, y;
// %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.

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 named template.java.

import java.io.*;
import java.util.*;
public class template {
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader(InputStream stream) {
reader = new BufferedReader(new InputStreamReader(stream), 32768);
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 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.

// InputReader template code above
static InputReader r = new InputReader(System.in);
static PrintWriter pw = new PrintWriter(System.out);
public static void main(String[] args) {
int a = r.nextInt();
int b = r.nextInt();
int c = r.nextInt()
pw.println(a + b + c);
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 "end" character (defaults to '\n'). Below is an annotated demonstration on different input/output scenarios.

# take in an integer n on a single line
n = int(input())
# take in integers n and m, both on the same line
n, m = map(int, input().split())
# read in a series of numbers on one line into a list
list = [int(x) for x in input().split()]
# read in a string
myStr = input()
# prints the string on its own line
print(myStr)

Example Solution - Weird Algorithm

Resources
GCPexample solution for this problem

C++

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

Note: If you went through the recommended sections of Sololearn from Choosing a Language, then you should be able to implement this yourself.

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.

#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

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

import java.util.*;
import java.io.*;
public class template {
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader() throws FileNotFoundException {
reader = new BufferedReader(new FileReader("problemname.in"));
tokenizer = null;

Some sources say to use

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

instead. There is no need for this since PrintWriter uses buffered output.

Python

The most intuitive way to do file IO 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")

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

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.

#include <iostream>
#include <vector>
using namespace std;
int main() {
freopen("paint.in","r",stdin);
// reuse standard in to read from "paint.in"
freopen("paint.out","w",stdout);
// reuse standard out to write to "paint.out"
vector<bool> cover(100);

Method 2

Use ifstream & ofstream.

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

Java

Method 1

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

Method 2

Alternatively, we can use the InputReader given above.

import java.util.*;
import java.io.*;
public class template {
static class InputReader {
BufferedReader reader;
StringTokenizer tokenizer;
public InputReader() throws FileNotFoundException {
reader = new BufferedReader(new FileReader("paint.in"));
tokenizer = null;

Python

See here for documentation about file I/O.

import sys
sys.stdin = open("paint.in", "r")
sys.stdout = open("paint.out", "w")
cover = [0] * 100
a, b = map(int, input().split())
c, d = map(int, input().split())
for i in range(a, b):
cover[i] = 1
for i in range(c, d):

Give Us Feedback on Input & Output!

Module Progress:

PrevNext