tags:

views:

87

answers:

3

Say I want to print:

============
Some message
============

And:

=======================
Other Message long one
=======================

The number of "=" changes based on the message length. What is the most efficient way to print this sort of a thing?

No boost, just STL please.

+7  A: 
std::string line(msg.length(), '=');
cout << line << "\n" << msg << "\n" << line << endl;
nice.............
+2  A: 

You don't specify how you are measuring "efficiency" in this context. Here's one solution that is efficient in terms of code you must write and number of allocations:

#include <string>
#include <iostream>

using namespace std;

void format(const std::string& msg)
{
    std::string banner(msg.length(), '=');
    cout << banner << endl
         << msg    << endl
         << banner << endl;
}

int main(int argc, char *argv[])
{
    format("Some message");
    format("Other message long one");
    return 0;
}

I can imagine other alternatives that avoid allocating a temporary string for the banners, but those might come at an increased cost of the actual printing.

Eric Melski
+2  A: 

iomanip variant, just for fun.

const std::string hello("hello world!");
std::cout << std::setfill('=') << std::setw( hello.length() + 1) << "\n"
          << hello << "\n";
          << std::setfill('=') << std::setw( hello.length() + 1 ) << "\n";
bb
Not going to put this fun into production code... it is need thought +1
+1 for not using '\n' and not expensive endl!
Richard Corden
endl - flushing buffer, we should use it when it need, not anywhere.
bb