Common input, output and arithmetic fragments for C++. See also the Python and Java versions.
The fragments assume using namespace std; and are meant to go inside
main. The headers each one needs are listed with it; <iostream> and
<string> are needed almost everywhere:
#include <iostream>
#include <string>
using namespace std;
Contents
Reading input
Values separated by spaces or newlines
>> skips over spaces and line breaks between values, so these work
whether the values are on one line or several:
int n;
double x;
string word; // one word (stops at a space)
cin >> n >> x >> word;A whole line
string line;
getline(cin, line); // the rest of the current line
Common problem: after cin >> n, the newline that ended the number is
still waiting, so the next getline returns an empty string. Skip it
first:
int n;
cin >> n;
cin >> ws; // skip the newline (and any blank space)
string title;
getline(cin, title); // now reads the next line
Splitting a line into pieces
Put the line in a stringstream (#include <sstream>) and read from it
with >>, just like from cin:
#include <sstream>
using namespace std;
string line;
getline(cin, line); // "Alice 17 92.5"
istringstream parts(line);
string name;
int age;
double score;
parts >> name >> age >> score;For commas (or another separator), use getline with the separator as a
third argument:
#include <sstream>
#include <vector>
using namespace std;
string line = "red,green,blue";
istringstream parts(line);
vector<string> fields;
string field;
while (getline(parts, field, ',')) {
fields.push_back(field); // "red", "green", "blue"
}Converting text to numbers
int n = stoi("17"); // 17
double d = stod("92.5"); // 92.5
long long big = stoll("10000000000");
string s = to_string(42); // "42"
stoi("3.5") returns 3 (it stops at the .), so use stod for values
that may have a decimal point.
A count followed by that many values
#include <vector>
using namespace std;
int n;
cin >> n;
vector<int> nums(n);
for (int i = 0; i < n; i++) {
cin >> nums[i];
}Everything until the end of the input
Use this when the problem does not say how many values or lines there
will be. The read inside the while is false once the input runs out:
int value;
while (cin >> value) {
// process value
}string line;
while (getline(cin, line)) {
if (!line.empty()) { // skip blank lines, if the problem allows
// process line
}
}Reading from a file
#include <fstream>
using namespace std;
ifstream file("data.txt");
if (!file) {
cout << "Could not open data.txt" << endl;
return 1;
}
string line;
while (getline(file, line)) {
// process line
}ifstream works with >> and getline exactly like cin. The file name
is relative to the folder the program runs in, which in Visual Studio is
usually the project folder (the one holding the .cpp file), not the
folder holding the .exe. If the file will not open, try the full path,
such as "C:\\Users\\me\\data.txt" (note the doubled backslashes).
Working with numbers
Converting between double and int
#include <cmath>
using namespace std;
int a = static_cast<int>(3.7); // 3 (drops the fraction)
int b = static_cast<int>(-3.7); // -3 (rounds toward zero)
double d = 5; // 5.0 (int to double is automatic)
double r = round(2.5); // 3.0 (halves round away from zero)
int r2 = static_cast<int>(round(3.7)); // 4
double r3 = round(3.14159 * 100) / 100; // 3.14
Division
When both sides are integers, / is integer division and throws away the
fraction:
7 / 2 // 3
7 / 2.0 // 3.5 -- one side is a double
static_cast<double>(a) / b // a/b with the fraction kept
-7 / 2 // -3 -- rounds toward zero
7 % 2 // 1 -- remainder
-7 % 2 // -1 -- sign of the left side
A common mistake: double avg = total / count; with int total, count
does integer division first, then converts. Write
static_cast<double>(total) / count.
Rounding up and down
#include <cmath>
using namespace std;
floor(3.7) // 3.0 (returns a double)
ceil(3.2) // 4.0
floor(-3.7) // -4.0
“Divide and round up” with positive integers (for example, boxes needed for 7 items at 2 per box) without going through doubles:
int ceilDiv(int a, int b) { // a >= 0, b > 0
return (a + b - 1) / b;
}
ceilDiv(7, 2) // 4
ceilDiv(8, 2) // 4
Overflow
The C++ standard lets the size of int vary between systems, but on the
computers you are likely to use it holds values up to about 2.1 billion.
Going past the limit silently gives a wrong (often negative) result. Use
long long (always at least up to about 9.2 × 10^18) for large values,
and convert before multiplying:
int a = 100000, b = 100000;
long long wrong = a * b; // overflowed as int first
long long right = static_cast<long long>(a) * b; // 10000000000
To see the limits on your system, use <climits>:
#include <climits>
using namespace std;
INT_MAX // 2147483647 on most systems
LLONG_MAX // 9223372036854775807
Other handy operations
#include <cmath> // abs for doubles, pow
#include <algorithm> // min, max
using namespace std;
abs(-5) // 5 (use the <cmath> version for doubles)
min(3, 8) // 3 -- both values must be the same type
max(3, 8) // 8
pow(2, 10) // 1024.0 (a double)
Math functions
All of these need #include <cmath>:
const double PI = acos(-1.0); // 3.14159... (M_PI is not standard C++)
sqrt(2.0) // 1.41421...
sin(30 * PI / 180) // 0.5 (approximately) -- trig uses radians
atan2(1.0, 1.0) * 180 / PI // 45 degrees
hypot(3.0, 4.0) // 5, distance from (0,0) to (3,4)
log(exp(1.0)) // 1 (natural log)
log10(100.0) // 2
exp(1.0) // 2.71828...
Floating-point results are rarely exact. Compare doubles with a tolerance
instead of ==:
if (fabs(a - b) < 1e-9) {
cout << "equal" << endl;
}Formatting output
By default cout prints 6 significant digits, so cout << 1234567.891
prints 1.23457e+06. For a specific number of decimal places, use
fixed and setprecision (#include <iomanip>):
#include <iomanip>
using namespace std;
double x = 3.14159;
cout << fixed << setprecision(2); // applies to everything printed after
cout << x << endl; // 3.14
cout << setw(8) << x << endl; // " 3.14" (8 wide; setw is NOT sticky)
cout << left << setw(8) << x << "|" << endl; // "3.14 |"
cout << "Total: $" << x << endl; // Total: $3.14
Without fixed, setprecision(2) means two significant digits
(3.1), not two decimal places.
printf (#include <cstdio>) works too, with the same codes as Java and
C:
#include <cstdio>
using namespace std;
printf("%.2f\n", x); // 3.14
printf("%8.2f\n", x); // " 3.14"
printf("%5d\n", 42); // " 42"
Use %d for int, %lld for long long, %f for double, and %s
for C strings (for a string, pass s.c_str()). Unlike Java, a
mismatch does not stop the program; it prints garbage instead:
printf("%d\n", 3.5); // a meaningless number, not 3
printf("%.2f\n", 42); // 0.00 (or another wrong value), not 42.00
Most compilers warn about these mismatches, so read the warnings.
Match the expected output exactly: extra spaces, missing blank lines, or a different number of decimal places can cause a solution to fail.
Example: average of the input
Reads numbers until the end of the input and prints their average to two decimal places:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double total = 0, value;
int count = 0;
while (cin >> value) {
total += value;
count++;
}
if (count > 0) {
cout << fixed << setprecision(2) << total / count << endl;
}
return 0;
}Example: sorting and searching
The goal of this example is to illustrate reading data, sorting it, and searching for values. It is written to be easy to follow rather than as fast as possible; for instance, the search simply checks every entry.
The program reads a file of names and ages (in years), sorts the entries
by age (and by name when two ages are equal), displays them all in
order, and then displays the ages of everyone named Parker. Suppose
people.txt holds one name and age per line (see
Reading from a file for where to put it):
Parker 17
Alex 16
Jordan 17
Parker 15
Casey 16
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
// One entry from the file: a name and an age in years.
struct Person {
string name;
int age;
};
// Decides the sorted order. Returns true if a goes before b: by age
// first, and by name when the ages are equal.
bool comesBefore(Person a, Person b) {
if (a.age != b.age) {
return a.age < b.age;
}
return a.name < b.name;
}
int main() {
// Read every name and age from the file.
ifstream file("people.txt");
if (!file) {
cout << "Could not open people.txt" << endl;
return 1;
}
vector<Person> people;
Person next;
while (file >> next.name >> next.age) {
people.push_back(next);
}
// Sort. sort calls comesBefore to decide which of two people goes
// first.
sort(people.begin(), people.end(), comesBefore);
// Display all entries in order.
for (Person p : people) {
cout << p.name << " " << p.age << endl;
}
// Search: check every entry and display the age of each one named
// Parker.
cout << "Ages of Parker:" << endl;
for (Person p : people) {
if (p.name == "Parker") {
cout << p.age << endl;
}
}
return 0;
}Output:
Parker 15
Alex 16
Casey 16
Jordan 17
Parker 17
Ages of Parker:
15
17
Names are compared character by character, and every uppercase letter
comes before every lowercase one, so "Zoe" sorts before "adam".