- Use
snprintf
format string- Use
boost::format
format string- Use
stringstream
format string
Concrete example
- Use
snprintf
format string
#include <stdio.h>
using std::string;
// 准备数据
string haha("haha");
int num = 3;
// 准备格式
string fmt("test string: %s. test number: %d");
char targetString[1024];
// 格式化,并获取最终需要的字符串
int realLen = snprintf( targetString,
sizeof(targetString),
fmt.c_str(),
haha.c_str(),
num );
Reference link : http://www.cplusplus.com/reference/cstdio/snprintf/
- Use
boost::format
format string
#include "boost/format.hpp"
// 准备数据
string haha("haha");
int num = 3;
// 准备格式
boost::format fmt("test string: %s. test number: %d");
// 格式化
fmt % haha % num;
// 获取最终需要的字符串
string targetString = fmt.str();
Reference link : https://www.boost.org/doc/libs/1_70_0/libs/format/example/sample_formats.cpp
- Use
stringstream
format string
#include <sstream>
using std::stringstream;
// 准备数据
string haha("haha");
int num = 3;
// 准备根据格式造字符串流
stringstream fmt; /* 或者使用 ostringstream */
// 造字符串流
fmt << "test string: " << haha << ". test number: " << num;
// 获取最终需要的字符串
string targetString = fmt.str();
Reference link : http://www.cplusplus.com/reference/ostream/ostream/operator<</