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

Started by
2 comments, last by Kiput 18 years, 8 months ago
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.)
Advertisement
#include <iomanip>os << std::left << std::setw(10) << "foobar";


Alternatively, with boost::format:
#include <boost/format.hpp>os << boost::format("%-10s") % "foobar";
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
HardDrop - hard link shell extension."Tread softly because you tread on my dreams" - Yeats
Interesting... Thanks!

This topic is closed to new replies.

Advertisement