It depends on what you mean by "easy".
Nothing "automatic".
As @salem c points out, you have to figure out the width of the output.
For a console window it could depend on what the user does, and what operating system you're using. That is quite a winding road, too much to post here.
If you're writing output to a file then you're probably in charge of deciding what the width is.
That said, let's say you can determine the width of the output, whatever that is.
This is a description of the "how", though the details are up to you:
1 2 3 4 5 6 7 8
|
int width = 80; // a typical assumption from history, not always correct for modern systems.
std::string = "Some String";
int half_string_length = string.length() / 2;
int half_output_width = width / 2;
int leading_spaces = half_output_width - half_string_length;
| |
At that point your task is to cout a string of spaces "leading_spaces" long, then your string, which could be one of the cout formatting methods, or just a string made of spaces.
This assumes, without checking, that "leading_spaces" is not negative.
There are simpler "formulae" related to the "midpoint" formula from algebra. This is a pedantic way to think of it.