Handge Handge -3 years ago 135
C++ Question

C++ How to make text health bar

I'm making something in C++, a text game to be precise, anyways I was wondering how would I make a Text Health Bar. '{' is the starting, '}' is the ending point of the health bar, ':' is the health so it makes something like {:::::::}. So I want the }, to stay where it is when the health is subtracted. How would you go about doing this?

What I have tried before was repeating a ':', based on the Health divided by your strength, but the '}' would follow the ':'. I had attempted to have a for loop to repeat the amount of spaces - health, and printing out a the character ' ' depending on how much spaces there should be. But none of these methods have worked.

So how would you Replace the colons I take out with spaces to keep a uniform length.

Answer Source

You need to print : for each strength point and fill the remaining with spaces (capacity). There are several methods.

Method 1: The loop

cout << '{';
for (unsigned int i = 0; i < capacity; ++i)
{
  if (i < strength)
  {
    cout << ':';
  }
  else
  {
    cout << ' ';
  }
}

Method 2: String of repeated characters

const std::string strength_text(strength, ':');
const std::string filler_text(capacity-strength, ' ');
cout << '{';
cout << strength_text << filler_text;
cout << '}';

Method 3: Setting field width

const std::string strength_text(strength, ':');
cout << '{';
cout << setw(capacity) << strength_text;
cout << '}';

You should research the setw modifier to see if it performs a right justified or left justified fill.

Other methods involve cursor positioning, which requires an external library.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download