C++ Input and Output — cout, cin, iomanip | Tutorials Logic
The iostream Library
C++ uses streams for I/O. A stream is a sequence of characters flowing to/from a device. The <iostream> header provides:
| Object | Direction | Description |
|---|---|---|
cout | Output | Standard output (console) - use << |
cin | Input | Standard input (keyboard) - use >> |
cerr | Output | Standard error (unbuffered) |
clog | Output | Standard log (buffered) |
#include <iostream>
#include <iomanip> // setw, setprecision, fixed
using namespace std;
int main() {
// Basic output
cout << "Hello, World!" << endl;
cout << "Line 1\nLine 2\n"; // \n is faster than endl
// Chaining
int a = 5, b = 10;
cout << "a = " << a << ", b = " << b << endl;
// Floating-point precision
double pi = 3.14159265358979;
cout << pi << endl; // 3.14159 (default 6 sig figs)
cout << fixed << setprecision(2) << pi << endl; // 3.14
cout << fixed << setprecision(8) << pi << endl; // 3.14159265
// Column alignment with setw
cout << left; // left-align
cout << setw(15) << "Name" << setw(10) << "Score" << endl;
cout << setw(15) << "Alice" << setw(10) << 95 << endl;
cout << setw(15) << "Bob" << setw(10) << 87 << endl;
// Boolean output
cout << boolalpha << true << " " << false << endl; // true false
// Hex / Oct / Dec
int n = 255;
cout << "Dec: " << dec << n << endl; // 255
cout << "Hex: " << hex << n << endl; // ff
cout << "Oct: " << oct << n << endl; // 377
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
// Read a single word (stops at whitespace)
string firstName;
cout << "Enter first name: ";
cin >> firstName;
cout << "Hello, " << firstName << "!" << endl;
// Read multiple values
int age;
double salary;
cout << "Enter age and salary: ";
cin >> age >> salary;
cout << "Age: " << age << ", Salary: " << salary << endl;
// Read a full line (including spaces)
cin.ignore(); // discard leftover newline from previous cin
string fullName;
cout << "Enter full name: ";
getline(cin, fullName);
cout << "Full name: " << fullName << endl;
// Input validation
int num;
cout << "Enter a number: ";
if (cin >> num) {
cout << "You entered: " << num << endl;
} else {
cerr << "Invalid input!" << endl;
}
return 0;
}
Level Up Your C plus plus Skills
Master C plus plus with these hand-picked resources
10,000+ learners
Free forever
Updated 2026
Related C++ Topics