Input and Output
Using cin, cout, and stream manipulators
Interview Relevant: Basic I/O operations
Input and Output in C++
C++ uses streams for input/output operations through iostream.
Stream Objects
- cout: Standard output stream (console)
- cin: Standard input stream (keyboard)
- cerr: Standard error stream (unbuffered)
- clog: Standard log stream (buffered)
Stream Manipulators
- endl: Insert newline and flush
- setw: Set field width
- setprecision: Set decimal precision
- fixed, scientific: Number format
Code Examples
Demonstrating various input/output operations and formatting.
cpp
1#include <iostream>
2#include <iomanip>
3using namespace std;
4
5int main() {
6 // Output
7 cout << "Enter your age: ";
8
9 // Input
10 int age;
11 cin >> age;
12
13 // Multiple inputs
14 string name;
15 cout << "Enter your name: ";
16 cin >> name; // Reads until whitespace
17
18 // Read entire line
19 cin.ignore(); // Clear buffer
20 string fullName;
21 getline(cin, fullName);
22
23 // Formatting
24 double pi = 3.14159265359;
25 cout << fixed << setprecision(2) << pi << endl; // 3.14
26 cout << setw(10) << "Hello" << endl; // Right-aligned
27
28 return 0;
29}