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::endl
flushes 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";
\n
writes 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.
Comments…