<iostream>
The <iostream>
header is a fundamental part of the C++ Standard Library, providing input and output functionality for console operations. It defines the standard input, output, and error streams, as well as overloaded operators for formatted I/O operations.
cin
, cout
, cerr
, and clog
std::cin
: Standard input streamstd::cout
: Standard output streamstd::cerr
: Standard error stream (unbuffered)std::clog
: Standard error stream (buffered)<<
and >>
operators for output and input respectively#include <iostream>
#include <string>
int main() {
std::string name;
int age;
std::cout << "Enter your name: ";
std::cin >> name;
std::cout << "Enter your age: ";
std::cin >> age;
std::cout << "Hello, " << name << "! You are " << age << " years old." << std::endl;
return 0;
}
cin
for input and cout
for output<<
operator for output and >>
for input#include <iostream>
#include <iomanip>
int main() {
double pi = 3.14159265358979;
std::cout << "Default: " << pi << std::endl;
std::cout << "Fixed: " << std::fixed << pi << std::endl;
std::cout << "Scientific: " << std::scientific << pi << std::endl;
std::cout << "Precision (3): " << std::setprecision(3) << pi << std::endl;
std::cout << "Width (10): " << std::setw(10) << pi << std::endl;
std::cout << "Left justified: " << std::left << std::setw(10) << pi << std::endl;
return 0;
}
fixed
, scientific
, setprecision
, and setw
#include <iostream>
#include <limits>
int main() {
int number;
while (true) {
std::cout << "Enter a positive integer: ";
if (std::cin >> number) {
if (number > 0) {
break;
} else {
std::cout << "Please enter a positive number." << std::endl;
}
} else {
std::cin.clear(); // Clear error flags
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Discard invalid input
std::cout << "Invalid input. Please enter a number." << std::endl;
}
}
std::cout << "You entered: " << number << std::endl;
return 0;
}
cerr
is unbuffered, making it useful for immediate error output<fstream>
headerstd::format
as a more modern alternative to some iostream formattingThe <iostream>
header is essential for console I/O operations in C++. It provides a type-safe, extensible, and formatted approach to input and output.
Key points to remember:
1. cin
for standard input, cout
for standard output
2. cerr
and clog
for error output (unbuffered and buffered respectively)
3. Use <<
for output operations and >>
for input operations
4. Supports chaining of I/O operations
5. Offers various formatting options through manipulators
By effectively using <iostream>
, C++ developers can create interactive console applications, handle user input, display formatted output, and manage error messages. While it may not be the most efficient for high-performance I/O, it provides a convenient and type-safe interface for most console I/O needs.