Input & Output
Authors: Darren Yao, Benjamin Qi, Nathan Wang, Allen Li
Prerequisites
Demonstrates how to read input and print output for USACO contests, including an example problem.
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:
sum 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), input and output are standard.
C++
<iostream>
Method 1 - 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, b, c; cin >> a >> b >> c;cout << "sum is " << a+b+c << "\n";// or cout << "sum is " << a+b+c << endl;}
<cstdio>
Method 2 - This library includes the
scanf
and
printf
functions, which
are slightly more complicated to use.
#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
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
Scanner
and System.out.print
Method 1 - 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 {static Scanner sc = new Scanner(System.in);public static void main(String[] args) {int a = sc.nextInt();int b = sc.nextInt();int c = sc.nextInt();System.out.print("sum 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.
BufferedReader
and PrintWriter
Method 2 - 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 {static BufferedReader r = new BufferedReader(new InputStreamReader(System.in));static PrintWriter pw = new PrintWriter(System.out);public static void main(String[] args) throws IOException {StringTokenizer st = new StringTokenizer(r.readLine());int a = Integer.parseInt(st.nextToken());int b = 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.
/** 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.** - The nextInt(), nextDouble(), and nextLong() methods will throw an* exception if there is no more data in the input.** @author: Kattis
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
:
Method | Description |
---|---|
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 PrintWriter
s 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
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 stringmyStr = input()# prints the string on its own lineprint(myStr)# take in an integer n on a single linen = int(input())# prints integer n with " test" after itprint(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 listnums = [int(x) for x in input().split()]# does the same thingnums = 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 linen, m = [int(x) for x in input().split()]# does the same thingn, 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.
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 | |||
---|---|---|---|
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.
Scanner
and System.out.print
Method 1 - Method 1
BufferedReader
and PrintWriter
Method 2 - Method 2
Kattio
With 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 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++
freopen
Method 1 - 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 filefreopen("problemname.out", "w", stdout);// cin reads from the file instead of standard inputint a, b, c; cin >> a >> b >> c;// cout prints to the file instead of standard outputcout << "sum is " << a+b+c << "\n";}
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;void setIO(string s) { // the argument is the filename without the extensionfreopen((s+".in").c_str(),"r",stdin);freopen((s+".out").c_str(),"w",stdout);}int main() {setIO("problemname");int a, b, c; cin >> a >> b >> c;cout << "sum is " << a+b+c << "\n";}
<fstream>
Method 2 - 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, b, c; fin >> a >> b >> c;fout << "sum 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 {static BufferedReader r;static PrintWriter pw;static {try {r = new BufferedReader(new FileReader("problemname.in"));pw = new PrintWriter(new FileWriter("problemname.out"));
Kattio
With // Kattio template code abovepublic class Main {static Kattio io;static {try {io = new Kattio("problemname");} catch(IOException e) {}}public static void main(String[] args) {
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 syssys.stdin = open("problemname.in", "r")sys.stdout = open("problemname.out", "w")
Example Solution - Fence Painting
Resources | |||
---|---|---|---|
USACO | Make sure to read this. |
For an explanation of the solutions below, check the Rectangle Geometry module.
C++
freopen
Method 1 - Method 1
<fstream>
Method 2 - Method 2
Java
Scanner
and PrintWriter
Method 1 - Method 1
BufferedReader
and PrintWriter
Method 2 - Method 2
Kattio
With 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:
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 newlinecout << ans << endl; // OK, newlinecout << ans << "\n"; // OK, newlinecout << ans << " "; // NOT OK, extra spacecout << ans << "\n\n"; // NOT OK, extra newline
Java
Java
pw.print(ans); // OK, no newlinepw.println(ans); // OK, newlinepw.print(ans+"\n"); // OK, newlinepw.print(ans+" "); // NOT OK, extra spacepw.print(ans+"\n\n") // NOT OK, extra newline
Python
Python
print(ans) # OK, newlineprint(ans,end='') # OK, no newlineprint(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!