【问题标题】:get the full string, while having format and args c++获取完整的字符串,同时具有格式和参数 c++
【发布时间】:2016-05-09 06:31:12
【问题描述】:

我正在使用 c++ 11。我想编写一个函数来获取格式化字符串和 args(不知道有多少,需要可变参数)并返回完整的字符串。

例如:

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"

有什么有效的方法吗?

【问题讨论】:

标签: c++ string c++11


【解决方案1】:

您可以使用Boost Format。还是老好sprintf()

char buf[1000];
int bytes = snprintf(buf, sizeof(buf), format, INDEX_RECORD_TYPE_TIMESTAMP,
    FORMAT_VERSION, optimizeBlockId, writeBlockId, timestamp);
assert(bytes < sizeof(buf));
string result(buf, min(sizeof(buf), bytes)); // now you have a C++ string

【讨论】:

    【解决方案2】:

    您可以按照上面的建议使用 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;
    }
    

    https://godbolt.org/g/hFwiS0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      相关资源
      最近更新 更多