Core Module
12 min forge
C++ Input & Output
Mastering cin, cout, and advanced formatting with iomanip.
C++ Input & Output
π What is it
Input/Output in C++ is primarily handled through the iostream library. cin is used for input (extraction operator >>) and cout is used for output (insertion operator <<).
β‘ When to use
Essential for interacting with users and competitive programming.
π§ Time complexity
std::cout: $O(K)$ where $K$ is the number of characters.- Fast I/O optimization: Using
ios_base::sync_with_stdio(false); cin.tie(NULL);significantly speeds up I/O for large data.
π» Code example
cpp Standard#include <iostream> #include <iomanip> int main() { int x; std::cout << "Enter a number: "; std::cin >> x; std::cout << "You entered: " << std::setw(5) << x << std::endl; return 0; }
β Common mistakes
- Forgetting
endlor\nto flush the buffer or move to the next line. - Using
std::cin >> stringwhen names have spaces (usegetlineinstead). - Not including
<iomanip>when using manipulators likesetprecision.