Right-center a string within another string?

Is there a way so that between two brackets that are a set distance apart, a string of varying length can be placed against the right bracket?

For context, I am making a table with the weather as a simple project. It is formatted as such:

--------------------------
| Temperature | Humidity |
--------------------------
| 75°| 50%|
| 110°| 0%|
--------------------------
NOTE: There are about 10-15 spaces before the numbers but the formatting removes them

I just want the numbers to float right in their little sections.

I just can't figure it out and I couldn't find any other threads on this. Thank you in advance!
Last edited on
You must edit your post and put the formatted text inside of [output] and [/output] tags.

You can use format manipulators inside <iomanip> in your code.

Like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Example program
#include <iostream>
#include <iomanip>
#include <string>

int main()
{
    const std::string Temperature = "Temperature";
    const std::string Humidity = "Humidity";

    struct Weather {
        double temperature;
        double humidity;
    } data[2] { { 75, 50},
                {110,  0} };
    
    std::string bar(2 + Temperature.length() + 3 + Humidity.length() + 2, '-');
    
    std::cout << bar << '\n';
    std::cout << "| " << Temperature << " | " << Humidity << " |\n";
    std::cout << bar << '\n';
    for (int i = 0; i < 2; i++)
    {
        std::cout << "| " << std::setw(Temperature.length()) << std::right << data[i].temperature << "°";
        std::cout << "| " << std::setw(Humidity.length()) << std::right << data[i].humidity << "%|\n";
    }

    std::cout << bar << '\n';
}

--------------------------
| Temperature | Humidity |
--------------------------   
|          75°|       50%|
|         110°|        0%| 
-------------------------- 


As of C++20, a nifty formatting library has been incorporated into the standard, but I have yet to actually try it out: https://en.cppreference.com/w/cpp/utility/format/format
Boost equivalent: https://www.boost.org/doc/libs/1_51_0/libs/format/doc/format.html
Last edited on
Topic archived. No new replies allowed.