Input & Output (Basics) Input & Output (Basics) I/O Basics
I/O Streams
#include <iostream>
int main () {
int i;
// read value into i
std::cin >> i;
// print value of i
std::cout << i << '\n';
}
Sources and Targets of Data
std::cin |
characters from stdin |
reads from buffer |
std::cout |
characters to stdout |
writes to buffer first,
output to console when buffer full |
std::clog |
characters to stderr |
writes to buffer first,
output to console when buffer full |
std::cerr |
characters to stderr |
immediatly writes to console |
Stream Operators
>> |
"get from" | source >> target |
<< |
"put to" | target << source |
- work for fundamental types and strings (support for other types can be added)
>>reads until next whitespace character (space, tab, newline, …)- can be chained:
#include <iostream>
int main () {
int i = 0;
double d = 0.0;
// read 2 values of different type:
std::cin >> i >> d;
// print 2 values and some text:
std::cout << "your input:\n"
<< i << " and " << d << '\n';
}
Avoid std::endl!
One often sees something like this in C++ code examples / tutorials:
std::cout << "some text" << std::endl;
std::cout << "more text" << std::endl;
- Each call to
std::endlflushes the output buffer and writes the output immediately. - This can lead to serious performance degradation, if done frequently.
C++'s I/O streams use buffers to mitigate the performance impact of
(potentially expensive) system input or output operations.
Output is collected until a minimum number of characters can be written.
Overusing std::endl interferes with this mechanism.
Do This Instead:
std::cout << "some text\nmore text\n";
\nwrites a line break- no premature flush of output buffer
- only one call to operator
<<(each additional call can create a small overhead)
Only use std::endl if you absolutely need to make sure that some
output needs to materialize immediately.
Formatted Printing C++23
As of C++23, the std::print and std::println functions
offer a convenient and highly performant way for printing formatted text.
The formatting syntax is modeled after that of the Python print function.
Precise control over prining floating point numbers is much more
convenient, less error prone and much faster compared to iostreams.
The
{fmt}
library can be used as an alternative
if you don't have a C++23 capable compiler available
(the standardization of std::print is largely based on it).
Prefer std::print over iostreams!
#include <print>
int main () {
int i = 12;
float f = 3.14159;
// print values (to stdout)
std::println("i={} f={}",i,f);
// print values to stderr
std::println(stderr,"i={} f={}",i,f);
// print with explicit new lines
std::print("i={}\nf={}\n",i,f);
}
std::print |
prints formatted text |
std::println |
prints formatted text followed by a new line |