Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sprintf in c++?

Tags:

c++

c

string

I'm searching for an sprintf in c++.

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

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

The query wont work.

like image 812
Roby Avatar asked Mar 16 '26 20:03

Roby


2 Answers

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

like image 79
Nawaz Avatar answered Mar 19 '26 12:03

Nawaz


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 );

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!