Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Incrementing a number in a sf::String?  (Read 3025 times)

0 Members and 1 Guest are viewing this topic.

epicasian

  • Newbie
  • *
  • Posts: 14
    • View Profile
Incrementing a number in a sf::String?
« on: October 16, 2010, 08:33:55 pm »
Hey, I'm trying to have the HUD in my game say something like
"You have collected: X items" and with X being the amount of items collected. Is it possible to have and integer in sf::String and be able to increment that number? Like the way printf() does:
printf("You have collected %i items!", x);

Thanks in advance.

Lupinius

  • Jr. Member
  • **
  • Posts: 85
    • View Profile
Incrementing a number in a sf::String?
« Reply #1 on: October 16, 2010, 08:56:05 pm »
You need a std::stringstream. You can add variables to those like you do witch std::cout.

vek

  • Newbie
  • *
  • Posts: 3
    • View Profile
Incrementing a number in a sf::String?
« Reply #2 on: October 17, 2010, 12:27:08 pm »
Just create a simple string converter class, like this:
Code: [Select]

#include <sstream>

class StringConverter
{
public:

static int toInt(const std::string& str)
{
std::istringstream stream(str);
int value;
stream >> value;
return value;
}

static std::string toString(int value)
{
std::ostringstream stream;
stream << value;
return stream.str();
}
};


and an example how to use it:
Code: [Select]

int health = 100;
sf::String Text("Health: " + StringConverter::toString(health));

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6287
  • Thor Developer
    • View Profile
    • Bromeon
Incrementing a number in a sf::String?
« Reply #3 on: October 17, 2010, 01:05:19 pm »
I'd prefer something like that. It is especially useful to concatenate lots of values with different types:
Code: [Select]
#include <sstream>

class MakeString
{
   public:
      template <typename T>
      MakeString& operator<< (const T& value)
      {
         mStream << value;
         return *this;
      }
       
      operator std::string() const
      {
         return mStream.str();
      }
       
   private:
      std::ostringstream mStream;
};

Usage:
Code: [Select]
int main()
{
    int health = 100;
    sf::String str(MakeString() << "Health: " << health);
}
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development: