3

I'm somewhat new to C++, coming from python. One piece of functionality I really miss is the string format operator. I've seen plenty of examples where this can be used in the printf() function, however, sometimes it is handy just to substitute placeholders in a string variable. Here is an example from python using the mysqldb module:

...
stmt = 'INSERT INTO %s(pid, starttime) VALUES("%s","%s")' % ('pids', int(p0.pid), episode[0][1])
cursor.execute(stmt)

Can you do something similar in C++. I'm not finding any examples googling.

nomadicME
  • 1,389
  • 5
  • 15
  • 35
  • 1
    Don't do that - you are opening yourself up to SQL injection! Do the regular parameter binding instead, using whatever facilities your database API of choice provides... – Branko Dimitrijevic Mar 27 '12 at 00:55
  • That was just an example. There are plenty of other applications for this functionality. – nomadicME Mar 27 '12 at 01:45

2 Answers2

5

You mean, you'd like to compose a string out of a number of string fragments and variables?

int someInt = 10;
std::wstringstream wss;
wss << L"Some string stuff and then " << someInt << L" which was an int" << std::endl;

You can then convert the contents of the wstringstream to other formats. To get a C string I believe the call would be wss.str().c_str().

  • That is pretty cumbersome. I was going to do that, but I thought there had to be a better way. There is no string substitution in C++? – nomadicME Mar 27 '12 at 01:41
  • Maybe slightly more cumbersome than string concatenation in Java. Otherwise it's a pretty straight-forward way to achieve that functionality without any additional libraries. – ShiggityShiggityShwa Mar 27 '12 at 01:51
  • Point taken about the additional libraries. Thanks. – nomadicME Mar 27 '12 at 02:07
  • Actually with "without additional libraries" you could just use `sprintf` that uses a similar syntax except it's all a function call. And before someone complains "too unsafe", there are some answers here precisely in Stack Overflow that show how to wrap it into a `strsprintf` that works with and delivers a eg.: `std::string`. – Luis Machuca Aug 07 '12 at 01:06
5

Check out the Boost format library.

It can do something like

str(format("writing %s,  x=%s : %d-th step \n") % "toto" % 40.23 % 50)
Ken Bloom
  • 57,498
  • 14
  • 111
  • 168