type
status
date
slug
summary
tags
category
icon
password
c++ | function | action |
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
Operator | Meaning | Example |
>> | "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:
Avoid
std::endl!One often sees something like this in C++ code examples / tutorials:
- 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:
\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.- 作者:KaiGuo
- 链接:https://blog.kaiguov5.com/article/cb5943fb-d337-4aab-a85e-d061609a3ac5
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。