获取完整字符串,同时使用format和args c++; 我使用C++ 11。我想写一个函数,它可以格式化字符串和参数(不知道有多少,需要可变),并返回完整的字符串

获取完整字符串,同时使用format和args c++; 我使用C++ 11。我想写一个函数,它可以格式化字符串和参数(不知道有多少,需要可变),并返回完整的字符串,c++,string,c++11,C++,String,C++11,例如: format = "TimeStampRecord Type=%u Version=%u OptimizeBlockID=%u WriteBlockID=%u Timestamp=%lu" INDEX_RECORD_TYPE_TIMESTAMP = 3; FORAMT_VERSION = 1; optimizeBlockId = 549; writeBlockId = 4294967295; timestamp = 1668; 返回值是一个字符串,如下所示: "TimeStampRe

例如:

format = "TimeStampRecord Type=%u Version=%u OptimizeBlockID=%u WriteBlockID=%u Timestamp=%lu"

INDEX_RECORD_TYPE_TIMESTAMP = 3;
FORAMT_VERSION = 1;
optimizeBlockId = 549;
writeBlockId = 4294967295;
timestamp = 1668;
返回值是一个字符串,如下所示:

"TimeStampRecord Type=3 Version=1 OptimizeBlockID=549 WriteBlockID=4294967295 Timestamp=1668"
有什么有效的方法吗?

您可以使用。或者好的旧的
sprintf()

charbuf[1000];
int bytes=snprintf(buf,sizeof(buf),格式,索引\记录\类型\时间戳,
格式(U版本、optimizeBlockId、writeBlockId、时间戳);
断言(字节
您可以按照上面的建议使用snprintf。 如果您想自己实现或使用自己的占位符:

#include "iostream"
#include "string"

void formatImpl(std::string& fmtStr) {
}

template<typename T, typename ...Ts>
void formatImpl(std::string& fmtStr, T arg, Ts... args) {
  // Deal with fmtStr and the first arg
  formatImpl(fmtStr, args...);
}

template<typename ...Ts>
std::string format(const std::string& fmtStr, Ts ...args) {
  std::string fmtStr_(fmtStr);
  formatImpl(fmtStr_, args...);
  return fmtStr_;
}


int main() {
  std::string fmtStr = "hello %your_placeholder world";
  std::cout << format(fmtStr, 1, 'a') << std::endl;
  return 0;
}
#包括“iostream”
#包括“字符串”
void formatImpl(std::string和fmtStr){
}
模板
void formatImpl(std::string和fmtStr、T参数、Ts…参数){
//处理fmtStr和第一个参数
formatImpl(fmtStr,args…);
}
模板
std::string格式(const std::string和fmtStr、Ts…args){
std::字符串fmtStr(fmtStr);
formatImpl(fmtStr,args…);
返回fmtStr;
}
int main(){
std::string fmtStr=“你好%your_占位符世界”;

std::cout,你是什么意思?,@Joachim Pileborg呢?我不知道缓冲区的大小。你知道格式的长度,你知道参数的数量和类型。这意味着你可以轻松创建一个
std::string
对象,该对象有足够的空间容纳参数的最大值,并将其用作调用的目标
snprintf
#include "iostream"
#include "string"

void formatImpl(std::string& fmtStr) {
}

template<typename T, typename ...Ts>
void formatImpl(std::string& fmtStr, T arg, Ts... args) {
  // Deal with fmtStr and the first arg
  formatImpl(fmtStr, args...);
}

template<typename ...Ts>
std::string format(const std::string& fmtStr, Ts ...args) {
  std::string fmtStr_(fmtStr);
  formatImpl(fmtStr_, args...);
  return fmtStr_;
}


int main() {
  std::string fmtStr = "hello %your_placeholder world";
  std::cout << format(fmtStr, 1, 'a') << std::endl;
  return 0;
}