根据消息长度打印自定义数量的标头分隔符

发布于 2024-07-16 09:16:08 字数 262 浏览 3 评论 0原文

假设我想打印:

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

And:

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

“=”的数量根据消息长度而变化。 打印这类东西最有效的方法是什么?

没有Boost,请只使用STL。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

宣告ˉ结束 2024-07-23 09:16:08
std::string line(msg.length(), '=');
cout << line << "\n" << msg << "\n" << line << endl;
std::string line(msg.length(), '=');
cout << line << "\n" << msg << "\n" << line << endl;
我早已燃尽 2024-07-23 09:16:08

您没有指定在这种情况下如何衡量“效率”。 这是一种在必须编写的代码和分配数量方面高效的解决方案:

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

我可以想象其他替代方案,避免为横幅分配临时字符串,但这些可能会增加实际打印的成本。

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.

最舍不得你 2024-07-23 09:16:08

iomanip 变体,只是为了好玩。

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";

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";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文