c++ - 使用可变大小的参数 vector 格式化字符串(例如,将参数 vector 传递给 std::snprintf)

标签 c++ printf

我正在寻找一种使用可变大小的变量 vector 来格式化字符串的方法。您认为这样做的最佳方法是什么?

我已经知道 std::snprintf 和 std::vsnprintf 但不幸的是,没有一个能立即解决我的问题。另外,使用递归模板的解决方案对我不起作用,因为我不能依赖在编译时完全定义的输入格式。

这是我要实现的功能的示例接口(interface)。

std::string format_variable_size(const char* format, const std::vector<int>& in) {
std::string out{};
....
return out;
}

示例输入和输出:

const char* format = "My first int is %d, my second int is: %d, my float is: %d";
std::vector<int> in = {1,2,3};

format_variable_size 将返回

out = "My first int is 1, my second int is: 2, my float is: 3"

另一个例子:

const char* format = "My first int is %d, my second int is: %d";
std::vector<int> in = {1,2};

format_variable_size 将返回

"My first int is 1, my second int is: 2"

谢谢,

最佳答案

如果您不反对使用 fmt ,我认为以下可能有效:

#include <numeric>

std::string format_variable_size(const char* fmt, std::vector<int> args){
  return std::accumulate(
    std::begin(args),
    std::end(args),
    std::string{fmt},
    [](std::string toFmt, int arg){
      return fmt::format(toFmt, arg);
    }
  );
}

std::vector<int> v = {1,2,3};
std::cout << format_variable_size("[{}, {}, {}]\n", v);

关于c++ - 使用可变大小的参数 vector 格式化字符串(例如,将参数 vector 传递给 std::snprintf),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57642240/

相关文章:

c - 如果不使用 C 中的逻辑运算符、关系运算符或选择结构,如何将 11,12 和 13 的值分配给所有等于 10 的值?

python - 用于电子邮件捕获的元编程 Python 脚本

c++ - 如何使用 gcc 和 intel 静态库进行编译?

c - 我无法理解打印第一个八个数组元素的数组的输出

c - 如何使用scanf读取带空格的文件的每一行?

c - 数据包嗅探器 : IP Header, 服务类型在 C 中输出 0

c++ - 打印时缺少小数点

c++ - 将 std::string 转换为 const char*,出现错误

c++ - 如何从预定义数组创建特定元素数组

python - 如何在 python 中使用 awk 对齐文本文件?