使用字符串格式运算符替换C++字符串

nom*_*cME 3 c++

来自python,我对C++有些新意.我真正想念的一个功能是字符串格式操作符.我已经看到很多可以在printf()函数中使用的例子,但是,有时候只是在字符串变量中替换占位符是很方便的.以下是使用mysqldb模块的python示例:

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

你能用C++做类似的事吗?我没有找到任何谷歌搜索的例子.

小智 5

您的意思是,您想用多个字符串片段和变量组成一个字符串?

int someInt = 10;
std::wstringstream wss;
wss << L"Some string stuff and then " << someInt << L" which was an int" << std::endl;
Run Code Online (Sandbox Code Playgroud)

然后您可以将 wstringstream 的内容转换为其他格式。要获取 C 字符串,我相信调用将是 wss.str().c_str()。


Ken*_*oom 5

查看Boost格式库.

它可以做类似的事情

str(format("writing %s,  x=%s : %d-th step \n") % "toto" % 40.23 % 50)
Run Code Online (Sandbox Code Playgroud)