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

C++ 根据消息长度打印自定义数量的标题分隔符,c++,stl,C++,Stl,假设我要打印: ============ Some message ============ 以及: “=”的数量将根据消息长度进行更改。打印这种东西最有效的方法是什么 没有推进,只需STL即可。std::string line(msg.length(),'='); std::string line(msg.length(), '='); cout << line << "\n" << msg << "\n" << line <

假设我要打印:

============
Some message
============
以及:

“=”的数量将根据消息长度进行更改。打印这种东西最有效的方法是什么

没有推进,只需STL即可。

std::string line(msg.length(),'=');
std::string line(msg.length(), '=');
cout << line << "\n" << msg << "\n" << line << endl;
cout
std::字符串行(msg.length(),'=');

cout在这种情况下,您没有具体说明如何衡量“效率”。以下是一个在您必须编写的代码和分配数量方面高效的解决方案:

#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;
}
#包括
#包括
使用名称空间std;
void格式(const std::string和msg)
{
字符串横幅(msg.length(),'=');

cout在此上下文中,您没有指定如何衡量“效率”。以下是一个在您必须编写的代码和分配数量方面有效的解决方案:

#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;
}
#包括
#包括
使用名称空间std;
void格式(const std::string和msg)
{
字符串横幅(msg.length(),'=');

coutiomanip变体,只是为了好玩

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";
const std::string hello(“hello world!”);

std::coutiomanip变体,只是为了好玩

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";
const std::string hello(“hello world!”);

std::cout基于消息长度打印的for循环有什么问题?基于消息长度打印的for循环有什么问题?不打算把这种乐趣放在生产代码中…需要思考+1endl-刷新缓冲区,我们应该在需要时使用它,而不是在任何地方。不打算把这种乐趣放在生产代码中…它需要思想+1endl-刷新缓冲区,我们应该在需要时使用它,而不是在任何地方。