Welcome to our deep dive into the fascinating world of C++ Manipulators! In this lesson, we'll explore what manipulators are, why they're useful, and how to use them effectively in your C++ coding projects. Let's get started!
Manipulators are special functions or operators that can be used with standard I/O streams (std::cout and std::cin) to format and modify the output or input in a more user-friendly or customized way. They are not built-in functions but are user-defined functions that can be added to the stream to manipulate the way data is displayed or accepted.
Manipulators come in handy when you want to:
std::setw, std::setprecision, etc. directlyTo use a manipulator, you simply insert it into the stream before the data you want to manipulate. Here's an example of a simple manipulator that outputs the current date and time:
#include <iostream>
#include <ctime>
// Define a manipulator for displaying the current date and time
std::ostream &date_time(std::ostream &os) {
std::time_t now = std::time(0);
std::tm* tm_now = std::localtime(&now);
os << "Current date and time: " << tm_now->tm_mday << "/"
<< tm_now->tm_mon + 1 << "/" << tm_now->tm_year + 1900
<< " " << tm_now->tm_hour << ":" << tm_now->tm_min << ":" << tm_now->tm_sec;
return os;
}
int main() {
std::cout << "Hello, World!\n" << date_time(std::cout);
return 0;
}In the example above, we've defined a manipulator called date_time that outputs the current date and time. In the main function, we've used this manipulator to display the current date and time along with "Hello, World!".
š Note: In the example above, we've defined a manipulator as a function that takes an std::ostream as a parameter and returns a reference to it. This allows us to chain manipulators together.
There are two main types of manipulators:
Built-in manipulators: These are part of the C++ Standard Library and include std::endl, std::boolalpha, std::noboolalpha, std::fixed, std::scientific, and std::setw, among others.
User-defined manipulators: These are custom manipulators that you create to suit your specific needs.
Now that you have an understanding of what manipulators are and how to use them, let's practice by creating a custom manipulator to format money amounts:
#include <iostream>
#include <iomanip>
// Define a manipulator for displaying money amounts
std::ostream &money(std::ostream &os) {
os << "USD $";
return os;
}
int main() {
double amount = 1234.56;
std::cout << money << std::fixed << std::setprecision(2) << amount << std::endl;
return 0;
}In this example, we've created a manipulator called money that adds the string "USD $" to the output stream. We've then used this manipulator along with std::fixed and std::setprecision to display a money amount in a user-friendly format.
What is a manipulator in C++?
What are the two main types of manipulators in C++?