The `std::cout
` object in C++ is a fundamental tool for
outputting data to the standard output, typically the console. It is part
of the standard library and resides in the `std
` namespace.
To use `std::cout
`, include the
`<iostream>
` header at the beginning of your code:
#include <iostream>
The `<<
` operator is used to send data to `std::cout
`. For example:
std::cout << "Hello, World!" << std::endl;
Here, `std::endl
` adds a newline and flushes the buffer.
`std::cout
` can output various data types. For example:
std::string hello = "Hello, World";
double x = 5;
std::cout << hello << std::endl;
std::cout << x << std::endl;
Multiple `<<
` operators can be chained for convenience:
double x=5,y=6;
std::cout << "x= " << x << " y= " << y << std::endl;
Use manipulators like `std::setw
` and
`std::setprecision
` for formatting. For example:
#include <iomanip>
std::cout << std::setw(10) << 123 << std::endl; // Aligns number in 10 columns
Avoid `using namespace std;
` to prevent namespace
pollution. Instead, use the `std::
` prefix or selective
using
declarations.
`std::cout
` outputs to the console by default, but can
be redirected using your shell's redirection mechanism.