【问题标题】:C++ iomanip expressionC++ iomanip 表达式
【发布时间】:2015-10-03 08:53:32
【问题描述】:

变量:

static const float    s_period[]    = { 100, 50, 25, 12, 5, 7, 3, 2, 1 };
static const unsigned s_timersCount = sizeof( s_period ) / sizeof( s_period[0] );
float  min = 10000000;
float  max = 0;
double sum = 0.0;

C++ 版本:

for( unsigned i = 0; i < s_timersCount; ++i ) {
   ...
   std::cout
      << "id: "         << std::setw(2) << (i+1)
      << ", expected: " << std::setw(3) << s_period[i]
      << ", min: "      << std::setw(3) << min
      << ", max: "      << std::setw(3) << max
      << ", avg: "      << std::fixed << std::setw(10) << std::setprecision(6) << avg
      << std::endl;
   std::cout.unsetf( std::ios_base::floatfield );
}

C 版:

for( unsigned i = 0; i < s_timersCount; ++i ) {
   ...
   printf( "id: %2d, expected: %3.0f, min: %3.0f, max: %3.0f, avg: %10.6f\n",
      ( i + 1 ), s_period[i], min, max, avg );
}

for 循环在此示例中很重要,因为我们必须为下一个循环重置 ios_base::floatfield

C++ 版本比 C 等价版本更冗长,您能提出一个更紧凑的 C++ 版本吗?

【问题讨论】:

  • 冗长并不总是一件坏事。 C++ 版本更容易阅读。
  • 如果fprintf() 是你真正想要的,为什么不用C++呢?
  • 请记住,C++ 版本也会在每次写入时刷新。 cerr 已设置 unitbufBoost.Format 允许在 C++ 流中使用类似 printf 的语法。
  • C 版本也更容易出错,例如为 unsigned int 指定 %d。 C++ 自动选择合适的重载。

标签: c++ c


【解决方案1】:

我不认为 C++ 方法的冗长有问题;事实上,它似乎比 C 版本更容易阅读和理解。

也就是说,您可以通过boost.format 使用 C++ iostreams 实现 printf 样式的格式化:

#include <boost/format.hpp>
#include <iostream>

using boost::format;
using boost::io::group;

int main() {
    const float    s_period[]    = { 100, 50, 25, 12, 5, 7, 3, 2, 1 };
    const unsigned s_timersCount = sizeof( s_period ) / sizeof( s_period[0] );
    float  min = 10000000;
    float  max = 0;
    double sum = 0.0;

    for (size_t i = 0; i < s_timersCount; ++i) {
        // ...
        std::cout << format("id: %2d, expected: %3.0f, min: %3.0f, max: %3.0f, avg: %10.6f\n")
                            % ( i + 1 ) % s_period[i] % min % max % sum;
    }

    return 0;
}

(live example)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多