I'm searching for an sprintf in c++.
I want to build a mysql query string but if I do it like (max_limit开发者_JAVA百科 is an const int
)
std::string query = "select * from bla limit " + max_limit;
The query wont work.
In C++11, this has been made too easy. Use std::to_string()
as:
std::string query = "select * from bla limit " + std::to_string(max_limit);
Done!
OLD SOLUTION, for those who still use 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
in many different ways, such as:
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 ;
See demo at ideone : http://ideone.com/J995r
And see my blog on this : Create string on the fly just in one line
You don't want sprintf, it doesn't work with strings. Something like this:
#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. You can then say:
std::string query = "select * from bla limit " + Str( max_limit );
Maybe you want to take a look at the boost::format lib.
It provides the syntax of sprintf with the convenience of c++.
So your example would be:
std::string str = (boost::format("select * from bla limit %d") % max_limit).str();
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);
精彩评论