Today we discuss some data processing tasks and introduce some useful functions in C++.
String Input
Sometimes we want to read an entire line of input (as a string $s$),
but the line may contains spaces so we cannot use cin >> s;
.
Instead use getline(cin, s);
.
If cin
or getline
fails, the return value is false
when evaluated as a boolean (falsy).
We can use while (cin >> n) {}
or while (getline(cin, s)) {}
to keep taking input until there is nothing left to read (useful when task does not specify input size).
To ignore $n$ upcoming characters in the input stream, use cin.ignore(n)
.
If $n = 1$ then the argument can be omitted.
For example, to read 4, July
, we can use:
// d: int, m: string cin >> d; cin.ignore(); cin >> m;
Sorting
Include the <algorithm>
library.
For an array $a$ populated with $n$ elements, use sort(a, a + n);
to sort the elements in ascending order.
File I/O
Usually, tasks take input from the standard input (typing on keyboard) and print output to the standard output (screen). The standard input and output together are called standard I/O (stdio).
We can use a convenient function freopen
to make our program replace stdio with file streams:
int main() { freopen("file.in", "r", stdin); freopen("file.out", "w", stdout); int n; cin >> n; cout << n << "\n"; }
Here, we read an integer from file.in
and output it to file.out
.
Notice when we comment out two freopen
calls, we are just reading and writing to stdio as normal.
You should do this if you want to test your program from the command line (or in HKOI's editor).
Note: if you are using a version of C++ older than C++11,
you need to include <cstdio>
for freopen
.
Otherwise, it is available in <iostream>
.
Auto Keyword
The auto
keyword can be used in place of an explicit type
when a compiler can infer a variable's type.
auto n = 4; // int
This is useful for avoiding complex types:
// Looping through a vector using an iterator for (auto it = v.begin(); it != v.end(); it++) { // it: vector<int>::iterator cout << *it << "\n"; }
Authored by s16f22