-
C++ > centrer du texte
- Output stream center alignment is always better done using custom functions
- Specialize your functions for certain scenarios
- Overload functions to provide multiple options for text formatting and alignment
- Utilize STL I/O manipulators library functions like std::setw() and std::setfill()
center the text in C++ by using the std::setw() I/O stream manipulator. Generally, Input/Output stream manipulators are STL helper functions that are supposed to be applied on insertion and extraction operators (<< , >>). std::setw() function is one of the manipulators responsible for setting the width parameter of the given stream. It takes a single parameter that specifies a new width of the stream.
In the following example code, we implemented a separate function named CenterWords() which takes a vector of strings and prints them centered. Note that this function also requires a maximum length number defined so that each string has the same padding.
This number should also be reasonably large to accommodate the largest possible string, which may be dependent on the specific scenarios. Moreover, CenterWords() function accepts an optional argument denoting a delimiter, which is utilized to separate strings in the vector.
#include <iostream> #include <vector> #include <iomanip>using std::cout; using std::endl; using std::string; using std::vector; using std::setw; using std::pair; constexpr int MAX_HORIZONTAL = 10; void CenterWords(vector<string> &vec, const char& delimiter = ‘|’) {for (auto &item : vec) { cout << setw(MAX_HORIZONTAL) << item.c_str() << setw(MAX_HORIZONTAL – item.size()) << delimiter; }cout << “n”; }int main() { vector<string> words = { “status”, “approval”, “profile”, “mole”, “extract”, “chance”, “nuance”, “wine” };CenterWords(words, ‘-‘); CenterWords(words); return 0; }
status – approval – profile – mole – extract – chance – nuance – wine – status | approval | profile | mole | extract | chance | nuance | wine |
Align Text in C++ Using Explicit Padding Size
Alternatively, we can take advantage of a simple loop-based method to generate fixed-size padding for the given strings and align text in C++. In this method, the function named – Center() accepts a string reference and an integer representing the padding length. Consequently, the string is printed in the center and includes a given number of whitespaces.
The next example demonstrates a basic usage for this technique to print multiple items in a single center-aligned column. Note that this method will be incompatible with non-fixed size strings, and this will be addressed in the later paragraphs.
– Code For C++ Center Justify
#include <iostream>
#include <vector>
#include <iomanip>using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::setw;
using std::pair;
void Center(string &str, const int padding)
{
for (int i = 0; i < padding; ++i) cout << ” “;
cout << str;
for (int i = 0; i < padding; ++i) cout << ” “;
}int main() {
vector<pair<string, string>> data = { {“item1”, “sold” },
{ “item2”, “in stock” },
{ “item3”, “sold” },
{ “item4”, “in stock” },
{ “item5”, “in stock” } };const auto padding = 3;
for (auto item : data) {
cout << “|”;
Center(item.first, padding);
cout << “|”;
cout << “n”;
}
return 0;
}– Program Output:
| item1 | | item2 |
| item3 |
| item4 |
| item5 |
C++ Text Alignment and Its Discontents
As you might have noticed in the previous code snippet, the Center() function is not usable in std::cout insertion statements. This raises the necessity to construct a formatter function in a way that can be included after the stream insertion operator (<<).
This is why we transform the Center() function so that it constructs a std::stringstream object in the local scope and appends all stream contents to it. However, it returns a std::string type and can be chained into other stream insertion operations.
– Code For C++ Justify Text
#include <iostream>
#include <vector>
#include <iomanip>using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::setw;
using std::pair;
std::string Center(string &str, const int padding){
std::stringstream ss;
for (int i = 0; i < padding; ++i) ss << ” “;
ss << str;
for (int i = 0; i < padding; ++i) ss << ” “;
return ss.str();
}int main() {
vector<pair<string, string>> data = { {“item1”, “sold” },{ “item2”, “in stock” },
{ “item3”, “sold” },
{ “item4”, “in stock” },
{ “item5”, “in stock” } };const auto padding = 3;
for (auto item : data) {
cout << Center(item.first, padding) << “|”;
}
return 0;
}– Program Output:
item1 | item2 | item3 | item4 | item5 | C++ Center Text With Automatic Left/Right Padding
Previous examples also showcased that if one needs to display different-sized strings aligned in separate columns, additional formatting is required. Specifically, the padding should be divided evenly into both sides of the strings.
The latter implies that we should have a fixed amount of places for each string, and this will be denoted by the max variable. The function itself should calculate the remainder of the padding by subtracting the maximum length to the size of the string and then dividing the result by two.
The above functionality is implemented in the following code snippet, where we process every std::pair of strings in each iteration and output them center-aligned in separate columns. Note that delimiters are supplied in the std::cout statement manually, but this can be also integrated into a function parameter to insert automatically.
Additionally, you may want to assign the default max value to the function parameter in case the caller does not supply the number.
– Code For C++ Text Alignment
#include <iostream>
#include <vector>
#include <iomanip>using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::setw;
using std::pair;
std::string Center(string &str, const int max)
{
std::stringstream ss;
int padding = max – str.size() / 2;
for (int i = 0; i < padding; ++i) ss << ” “;
ss << str;
for (int i = 0; i < padding; ++i) ss << ” “;
return ss.str();
}int main() {
vector<pair<string, string>> data = { {“item1”, “sold” },{ “item2”, “in stock” },
{ “item3”, “sold” },
{ “item4”, “in stock” },
{ “item5”, “in stock” } };const int max = 10;
for (auto item : data) {
cout << “|” << Center(item.first, max) << “|”
<< Center(item.second, max) << “| ” << “n”;
}
return 0;
}– Program Output:
| item1 | sold | | item2 | in stock |
| item3 | sold |
| item4 | in stock |
| item5 | in stock |
Use std::setfill Manipulator for Padding With Specific Character
Another useful manipulator is the std::setfill(), which takes a single character argument and sets it as the fill character for the output stream. This method is used in the next example where an arbitrary character (#) is set for the stream to fill, and then std::setw() is included to specify the number of fill characters. Notice that the order of these two manipulators does not matter in the statement.
– Code – C++ std::setfill Manipulator:
#include <iostream>
#include <iomanip>
int main() {
cout << “default fill: |” << setw(4) << 99 << “|n”
<< “setfill(‘#’): |” << setfill(‘#’)
<< setw(4) << 99 << “|n”;
return 0;
}– Program Output:
default fill: | 99| setfill(‘#’): |##99|
How To Fill Padding Places With Specific Characters
You can fill padding places with specific characters by implementing std::setfill()-like functionality in the latest Center() function. This version of the function will take a third parameter, and it will represent the fill character for the output stream.
Furthermore, in the example below, we specified an empty space as the default value for this parameter to make the function more flexible. The following code snippet shows the basic usage of the modified Center() function.
– Code For C++ Fill Padding Places
#include <iostream>
#include <vector>
#include <iomanip>using std::cout;
using std::endl;
using std::string;
using std::vector;
using std::setw;
using std::pair;
std::string Center(string &str, const int max, const char c = ‘ ‘)
{
std::stringstream ss;
int padding = max – str.size() / 2;
for (int i = 0; i < padding; ++i) ss << c;
ss << str;
for (int i = 0; i < padding; ++i) ss << c;
return ss.str();
}int main() {
vector<pair<string, string>> data = { {“item1”, “sold” },{ “item2”, “in stock” },
{ “item3”, “sold” },
{ “item4”, “in stock” },
{ “item5”, “in stock” } };const int max = 10;
for (auto item : data) {
cout << “|”
<< Center(item.first, max, ‘-‘) << “|”
<< Center(item.second, max, ‘-‘) << “|”
<< “n”;
}
return 0;
}– Program Output:
|——–item1——–|——–sold——–| |——–item2——–|——in stock——|
|——–item3——–|——–sold——–|
|——–item4——–|——in stock——|
|——–item5——–|——in stock——|
Final Thoughts
So far, we have explored several scenarios for C++ text alignment and discussed methods to manipulate output streams. Here are some key points to be aware of:
These techniques should help you build the foundation for more advanced output stream formatting handling in C++. Moreover, try to identify and construct several text formatting helper functions that might be used for common programming tasks so that you’re able to utilize them in future projects.