Jump to content
  • Advertisement
Sign in to follow this  
Kiput

sprintf( FooBar, "%-10s", Foo ) in C++?

This topic is 4839 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi, just a quick question. Is there anyway I could do something like this in C++ with iostreams: sprintf( Foobar, "%-10s", Foo );? Yes, I know there is width( ) function, but it doesn't seem to work with negatives (if we write ,,%-10s'' instead of ,,%10s'' the string is padded from right, not from left). Any suggestions? (I don't wan't to use sprintf, because I have UTF-8 strings and it screws my display. Something like width( ), where I can enter actual length manually would be good.)

Share this post


Link to post
Share on other sites
Advertisement
there must be a better way:

struct padleft
{
padleft(int w): width( w){}
int width;
};

struct padlproxy
{
std::ostream &os;
const padleft &pad;
padlproxy(std::ostream &o, const padleft &p): os( o), pad( p){}
};

template <typename T>
std::ostream& operator<<(padlproxy &pp, const T &t)
{
std::stringstream ss;
ss << t;
size_t plen = pp.pad.width - ss.str().size();
std::string pad( plen > 0 ? plen : 0, ' ');
return pp.os << ss.str() << pad;
}

padlproxy operator<<(std::ostream &os, const padleft &pad){ return padlproxy( os, pad);}

int main(void)
{
printf( "|%-10s|\n", "foo");
std::cout << "|" << padleft( 10) << "foo" << "|\n";
}

... and your milage may vary.. that worked for me though :p

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!