Ch2.14: A + B
Basic Input and Output
A simple program that reads two integers and prints their sum. This demonstrates
scan for input and println for output:
#include <fast_io.h>
#include <cstddef>
int main()
{
using namespace fast_io::iomnp;
std::size_t a, b;
scan(a, b);
println(a + b);
}
What is a Manipulator?
In fast_io, a manipulator is a helper object that changes how
input or output is interpreted or formatted. Instead of relying on unsafe format strings,
manipulators make the intent explicit in the type system.
Manipulators are defined in the namespace fast_io::manipulators, which is aliased
as fast_io::mnp for convenience. They make input and output safer, more explicit,
and more portable than traditional stdio or iostream.
For example:
hex_get(a)— tellsscanto read the variableain hexadecimal.hex(a)— printsain lowercase hexadecimal.hexupper(a)— printsain uppercase hexadecimal.base_get<N>(a)— readsain base N (2 ≤ N ≤ 36).base<N>(a)— printsain base N.
Hexadecimal Manipulators
fast_io provides manipulators to read and print numbers in hexadecimal.
hex_get reads input in hex, while hex and hexupper
print output in lowercase or uppercase hex respectively:
#include <fast_io.h>
#include <cstddef>
int main()
{
using namespace fast_io::iomnp;
::std::size_t a, b;
scan(hex_get(a), hex_get(b));
println(hex(a + b), " ", hexupper(a + b));
}
Base-N Manipulators
Manipulators also support arbitrary bases from 2 to 36. Here’s an example using base 36:
#include <fast_io.h>
#include <cstddef>
int main()
{
using namespace ::fast_io::iomnp;
::std::size_t a, b;
scan(base_get<36>(a), base_get<36>(b));
println(base<36>(a + b));
}
About Manipulators
fast_io defines a rich set of manipulators to control input and output formatting.
For convenience, the namespace fast_io::manipulators is aliased as fast_io::mnp.
base_get<N>— reads numbers in base N (where 2 ≤ N ≤ 36).base<N>— prints numbers in base N.hex— shorthand forbase<16>.hexupper— shorthand forbase<16,true>, printing hex digits in uppercase.
These manipulators make it easy to work with different numeric bases without relying on unsafe format strings.