2

我有一个程序,它有一个字符串(需要格式化)并从外部源获取一组元素。
字符串必须使用集合的元素格式化,即 std::string。
我无法手动格式化字符串,例如:

// Just examples
sprintf(test, "%s this is my %s. This is a number: %d.", var[0], var[1], etc..);        // i can't do this
fmt::printf("%s this is my %s. This is a number: %d.", var[0], var[1], etc..);          // i can't do this (i also have fmt library)

这是因为集合中的元素数量是可变的。
我想做的是尽可能有效地格式化字符串。

这是代码:

std::string test = "%s this is my %s. This is a number: %d.";
std::vector<std::string> vec;

vec.push_back("Hello");
vec.push_back("string");
vec.push_back("5");


// String Formatting
std::size_t found;
for (auto i : vec)
{
    found = test.find("%");
    if (found != std::string::npos)
    {
        test.erase(found, 2);
        test.insert(found, i);
    }
}

std::cout << test;

注意 1:我使用 std::vector 来管理集合的元素,但我可以使用任何其他结构。

这就是为什么我没有将定义放在代码中。

此外,如果我有一个带有百分比的字符串,我编写的代码不起作用,例如:

std::string test = "%s this is a percentage: %d%%. This is a number: %d.";
// Output = "Hello this is a percentage: string5. This is a number: %d."

总之:用多个元素格式化字符串的最有效方法是什么?
即使不使用向量,但使用另一种结构。还是使用 fmt 或 boost?(也许提升会降低效率)
我的开发环境是 Visual Studio 2019。

4

1 回答 1

3

您可以使用最近添加的 {fmt} dynamic_format_arg_store( https://github.com/fmtlib/fmt/releases/tag/6.2.0 ) 来执行此操作:

#include <fmt/format.h>

int main() {
  fmt::dynamic_format_arg_store<fmt::format_context> args;
  args.push_back("Hello");
  args.push_back("string");
  args.push_back("5");
  fmt::vprint("{} this is my {}. This is a number: {}.", args);
}

这打印(https://godbolt.org/z/jUbbUi):

Hello this is my string. This is a number: 5.

请注意,{fmt} 使用{}而不是%替换字段。

于 2020-05-06T16:00:45.067 回答