我正在用c ++搜索sprintf。
我想构建一个mysql查询字符串,但如果我这样做(max_limit是const int
)
std::string query = "select * from bla limit " + max_limit;
查询不起作用。
答案 0 :(得分:9)
在C ++ 11中,这太简单了。使用std::to_string()
作为:
std::string query = "select * from bla limit " + std::to_string(max_limit);
完成!
OLD SOLUTION,适用于那些仍在使用C ++ 03的人。
使用stringbuilder
并动态创建std::string
:
std::string query = stringbuilder() << "select * from bla limit " << max_limit;
其中stringbuilder
实现为:
struct stringbuilder
{
std::stringstream ss;
template<typename T>
stringbuilder & operator << (const T &data)
{
ss << data;
return *this;
}
operator std::string() { return ss.str(); }
};
您可以通过多种不同方式使用stringbuilder
,例如:
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 ;
请参阅ideone上的演示:http://ideone.com/J995r
答案 1 :(得分:6)
你不想要sprintf,它不能用于字符串。像这样:
#include <sstream>
#include <string>
template <typename T>
std::string Str( const T & t ) {
std::ostringstream os;
os << t;
return os.str();
}
将完成这项工作。然后你可以说:
std::string query = "select * from bla limit " + Str( max_limit );
答案 2 :(得分:4)
也许你想看一下boost::format lib。 它提供了sprintf的语法,方便了c ++ 所以你的例子是:
std::string str = (boost::format("select * from bla limit %d") % max_limit).str();
答案 3 :(得分:0)
或者只是使用宏?
#define QueryString(msg) ((static_cast<std::ostringstream&>(std::ostringstream().seekp(0, std::ios_base::cur)<<msg)).str())
使用方法:
std::string query = QueryString("select * from mytable where x="<<30);