cin, cout & cerr
The standard streams (<iostream>)
| Stream | Purpose | Buffered? |
|---|---|---|
std::cout | normal output | yes |
std::cin | keyboard input | yes |
std::cerr | error messages | no (appears immediately) |
std::clog | log messages | yes |
Reading input with >>
int age;
std::cin >> age;
>>is the extraction operator- It skips leading whitespace (spaces, tabs, newlines)
- It stops at the next whitespace — so
std::cin >> name;reads only one word - It converts text to the variable's type automatically
Chaining
int a, b;
std::cin >> a >> b; // user can type "3 4" or "3<Enter>4"
std::cout << a + b << '\n';
Why cerr?
Output to cerr and cout can be separated: ./app > results.txt saves cout to a file but errors still appear on screen.
Reading until input ends
int x, sum = 0;
while (std::cin >> x) sum += x; // stops at end of input or invalid data
(End of input: Ctrl+D on Linux/macOS, Ctrl+Z then Enter on Windows.)
Prompting
Always tell the user what to type:
std::cout << "Enter your monthly income: ";
std::cin >> income;
Speed tip (competitive programming)
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
makes cin/cout much faster for huge inputs (don't mix with printf/scanf after this).
Example
#include <iostream>
int main() {
std::string name;
int age;
double income, rent;
std::cout << "Enter your first name: ";
std::cin >> name;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Enter monthly income and rent: ";
std::cin >> income >> rent;
std::cout << "\nHi " << name << " (" << age << ")!\n";
std::cout << "After rent you have Rs. " << income - rent << " left.\n";
if (rent > income * 0.5)
std::cerr << "Warning: rent is more than half of your income\n";
int amount, count = 0, sum = 0;
while (std::cin >> amount) { // read numbers until input ends
sum += amount;
count++;
}
std::cout << "Read " << count << " extra expenses totalling Rs. " << sum << '\n';
return 0;
}
/* Output:
Enter your first name: Enter your age: Enter monthly income and rent:
Hi Asha (24)!
After rent you have Rs. 30000 left.
Read 3 extra expenses totalling Rs. 4350
*/