c++ - 提供格式化字符串作为参数的现代方法

标签 c++ string string-formatting

我有一个与 std::string formatting like sprintf 非常相似的问题或 this question但是这些已经很老了,所以我敢于重试以收集一些方法。

我想要一个函数/方法,它采用参数来定义带有一些变量的格式化字符串,很像 printf/sprintf。例如,它可以是一个方法 send_string(ARGS) ,它会格式化一个字符串并将其发送给某个接收者。例如:

server->send_message("value1: %d, value2: %0.3f, value3: %s", 2, 3.14, "hello world");

我知道流的概念,我知道 boost::format。但我想知道什么是最不冗长的方法没有不必要的依赖

这是我想到的:

  • 使用基于流的方法 - 结果如下:

    server->msg_out() << "value1: " << 2 
                      << ", value2: " << 3.14 
                      << ", value3: '" << "hello world" << "'";
    

    这对我来说看起来最合理,但它非常冗长,很难看出输出会是什么样子。特别是当您尝试实现表格输出或实际值的特殊格式时。从好的方面来说,您没有任何依赖关系。

  • 使用基于 C 的变量参数。看起来像上面的示例,尽管它已被弃用、容易出错且不灵活,但它已广为人知并被广泛使用。

  • 使用 Boost.Format

    server->send_message(boost::format(
                "value1: %d, value2: %0.3f, value3: %s") % 2 % 3.14 % "hello world"));
    

    或(避免 API 中的依赖项):

    server->send_message(
        boost::str(
            boost::format(
                "value1: %d, value2: %0.3f, value3: %s") % 2 % 3.14 % "hello world")));
    

    这似乎是最sprintf 的基于 C++ 的方法。但我也不喜欢这种方法 - 它非常,语法残酷,也非常冗长,并且引入了对 Boost 的依赖(如果您还没有使用它的话)。

所以目前我会决定支持基于流的方法,但每次我使用它时我都会想:一定有更优雅的方法!

有没有我还没有想到的更简单的方法?

最佳答案

您可能会使用 Qt 或从中获得灵感 QString::arg职能;它的格式字符串为 %1 ... %9 但参数是通过 arg 重载函数给出的,例如

QString str;
long num;
double dbl;
QString outstr = 
 QString("str=%1 num=%2 dbl=%3").arg(str).arg(num).arg(dbl);

所以输入是通过重载 arg 但格式字符串对本地化更友好。

关于c++ - 提供格式化字符串作为参数的现代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34568310/

相关文章:

regex - python : extract all placeholders from format string

c++ - 使用 BOOST_FOREACH 修改 std::vector 中的指针

c++ - curl 慢速多线程 dns

c++ - CreateProcess - lpApplicationName 与 lpCommandLine

python - 获取字符串中数值列表的最简洁方法

java - 这两种字符串格式有什么区别?

c++ - 在 Visual Studio 2010 中从 .h 和 .lib 创建 .dll

string - 在 Bash 中比较两个字符串时出现 "command not found"错误

C - 从字符串中提取大写字母

python - 有没有办法在执行连接操作时证明子字符串的合理性