String Formatting
String formatting allows you to control the appearance of strings when they are printed or displayed. In C++, you can use the std::cout
object along with formatting manipulators to format strings.
One common use case for string formatting is to control the number of decimal places when printing floating-point numbers. For example, if you have a variable pi
with the value 3.14159265359 and you want to display it with 2 decimal places, you can use the std::fixed
and std::setprecision
manipulators from the <iomanip>
header. Here's an example:
1#include <iostream>
2#include <iomanip>
3
4int main() {
5 double pi = 3.14159265359;
6
7 // Format pi to display with 2 decimal places
8 std::cout << "Pi: " << std::fixed << std::setprecision(2) << pi << std::endl;
9
10 return 0;
11}
In this example, we start with a variable pi
with the value of 3.14159265359. We use the std::cout
object to display the string "Pi: " followed by the formatted value of pi
. The std::fixed
manipulator ensures that the number is displayed in fixed-point notation, and the std::setprecision
manipulator sets the precision (number of decimal places) to 2.
The output of the code will be:
1Pi: 3.14
String formatting in C++ provides various other manipulators and options to control the appearance of strings, such as setting the width, alignment, padding, and more. You can explore the <iomanip>
header for more information and options.
xxxxxxxxxx
int main() {
double pi = 3.14159265359;
// Format pi to display with 2 decimal places
std::cout << "Pi: " << std::fixed << std::setprecision(2) << pi << std::endl;
return 0;
}