Sprintf in C ++?

I am looking for sprintf in C ++.

I want to build a mysql query string, but if I like it (max_limit is const int )

 std::string query = "select * from bla limit " + max_limit; 

The request does not work.

+2
source share
4 answers

In C ++ 11, this was done too simply. Use std::to_string() as:

 std::string query = "select * from bla limit " + std::to_string(max_limit); 

Done!


OLD SOLUTION, for those still using C ++ 03.

Use stringbuilder and create std::string on the fly as:

 std::string query = stringbuilder() << "select * from bla limit " << max_limit; 

where stringbuilder is implemented as:

 struct stringbuilder { std::stringstream ss; template<typename T> stringbuilder & operator << (const T &data) { ss << data; return *this; } operator std::string() { return ss.str(); } }; 

You can use stringbuilder many ways, for example:

 std::string g(int m, int n) { //create string on the fly and returns it if ( m < n ) return stringbuilder() << m << " is less than " << n ; return stringbuilder() << n << " is less than " << m ; } void f(const std::string & s ); //call f while creating string on the fly and passing it to the function f(stringbuilder() << '{' << pc << '}' ); //passed as std::string //this is my most favorite line std::string s = stringbuilder() << 23 << " is greater than " << 5 ; 

Watch the demo at ideone: http://ideone.com/J995r

And look at my blog on this: Create a line "on the fly" in only one line

+9
source

You do not need sprintf, it does not work with strings. Something like that:

 #include <sstream> #include <string> template <typename T> std::string Str( const T & t ) { std::ostringstream os; os << t; return os.str(); } 

will do the job. Then you can say:

 std::string query = "select * from bla limit " + Str( max_limit ); 
+6
source

You might want to take a look at boost :: format lib. It provides sprintf syntax with C ++ convenience.
So your example:

 std::string str = (boost::format("select * from bla limit %d") % max_limit).str(); 
+4
source

Or just use a macro? #define QueryString(msg) ((static_cast<std::ostringstream&>(std::ostringstream().seekp(0, std::ios_base::cur)<<msg)).str())

Usage: std::string query = QueryString("select * from mytable where x="<<30);

0
source

All Articles