CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Jan 2010
    Location
    Maryland
    Posts
    1

    Question Coding Question not on Google

    Alrighty, im trying to make a game using Health bars that are illustraed by the following

    "Health: |||||||||||||||||"

    and i wanted to know if p1Health was my int variable (int p1Health; ) representing player 1's health, how i can make that output the same number of "|"s. So if p1Health = 20, i want the code to output "||||||||||||||||||||".

    (I know i could use an 'if' statement or a 'switch:case' but i would like to do it with the least amount of code possible because there is alot more elements to this game, and i don't want the health bar to take up 1000 lines. (there are two players in this game, so the shorter the code the better)

    Is there a way i can use my variable p1Health and put it into setw()?
    *because setw(p1Health) didnt work.

  2. #2
    Join Date
    Jan 2009
    Posts
    1,689

    Re: Coding Question not on Google

    Code:
    string HealthBar(unsigned int health){
       string output;
       for (unsigned int i = 0; i < health; ++i){
          output += '|';
       }
       return output;
    }

  3. #3
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Coding Question not on Google

    Quote Originally Posted by TheMightyJoda View Post
    Alrighty, im trying to make a game using Health bars that are illustraed by the following

    "Health: |||||||||||||||||"

    and i wanted to know if p1Health was my int variable (int p1Health; ) representing player 1's health, how i can make that output the same number of "|"s. So if p1Health = 20, i want the code to output "||||||||||||||||||||".
    Code:
    #include <string>
    #include <iostream>
    
    int main()
    {
        int p1Health = 10;
        std::string strHealth(p1Health, '|');
        std::cout << strHealth;
    }
    Regards,

    Paul McKenzie

  4. #4
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Coding Question not on Google

    Quote Originally Posted by ninja9578 View Post
    Code:
    string HealthBar(unsigned int health){
       string output;
       for (unsigned int i = 0; i < health; ++i){
          output += '|';
       }
       return output;
    }
    No need for a function -- one of the std::string constructors does this already.

    Regards,

    Paul McKenzie

  5. #5
    Join Date
    Jan 2009
    Posts
    1,689

    Re: Coding Question not on Google

    Oh, I knew wxString did that, wasn't sure if std::string did. Oh well, yeah, use that.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured