在c语言中,对于char类型,我们有spirntf、snprintf进行格式化输出,但是string类型对格式化输出的支持不是很理想;
例如对于功能
sprintf(str, "bob's address is %s, and kevin's address is %s\n", add1, add2);
可以定义一个stringstream
std::stringstream fmt;更类似sprintf类似的功能,可以借助boost来实现:
fmt << "bob's address is " << add1 << " and kevin's address is " << add2;
strcpy(str, fmt.c_str());
#include <string>
#include <boost/format.hpp>
int main() {
std::string add1,add2;
// apply format
boost::format fmt = boost::format("bob's address is %s, and kevin's address is %s") % add1 % add2;
// assign to std::string std::string str = fmt.str(); std::cout << str << "\n";
}