简体   繁体   中英

C++ iomanip expression

Variables:

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++ version:

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 version:

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 );
}

The for loop is important in this example because we have to reset ios_base::floatfield for the next loop.

The C++ version is more verbose than the C equivalent, can you propose a more compact C++ version?

I don't consider the verbosity of the C++ approach to be problematic; in fact, it seems to be easier to read and understand than the C version.

That said, you can achieve printf-style formatting using C++ iostreams via boost.format :

#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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM