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 endl or \n to flush the buffer or move to the next line.
  • Using std::cin >> string when names have spaces (use getline instead).
  • Not including <iomanip> when using manipulators like setprecision.