需要帮助编写 for 循环以在字符串周围创建边框



您好,我想知道如何编写一个将在字符串周围创建边框的 for 循环。我有几个不同长度的字符串,我希望循环打印带有边框的字符串,这样它看起来更有凝聚力,所以我不必手动更改它。谢谢!!

我需要获得由边框包围的"财富",如下所示,但使用 for 循环。

以下是选择的命运:

一个新的机会在岔路口等着你,

早起的鸟儿得到虫子,但第二只老鼠得到奶酪,

你巧妙地伪装成负责任的成年人,

生活中最好的东西不是东西,

忘记伤害;永远不要忘记善良,

向悲观主义者借钱,他们不指望回来

cout << " |=========================================================| n";
cout << " |" <<fortune[rand_index]<<" | n";
cout << " |=========================================================| n";
#include <iostream>
#include <string>
#include <cstddef>
void print_with_border(std::string const &str)
{
std::cout.put('+');
for (std::size_t i{}; i < str.length() + 2; ++i)
std::cout.put('-');
std::cout << "+n| " << str << " |n+";
for (std::size_t i{}; i < str.length() + 2; ++i)
std::cout.put('-');
std::cout << "+n";
}

int main()
{
std::string fortunes[]{
"A new opportunity awaits you at the fork of the road.",
"The early bird gets the worm, but the second mouse gets the cheese.",
"You are cleverly disguised as responsible adult.",
"The best things in life aren't things.",
"Forget injuries; never forget kindnesses.",
"Borrow money from a pessimist, They don't expect it back."
};

for (auto const &f : fortunes)
print_with_border(f);
}

输出:

+-------------------------------------------------------+
| A new opportunity awaits you at the fork of the road. |
+-------------------------------------------------------+
+---------------------------------------------------------------------+
| The early bird gets the worm, but the second mouse gets the cheese. |
+---------------------------------------------------------------------+
+--------------------------------------------------+
| You are cleverly disguised as responsible adult. |
+--------------------------------------------------+
+----------------------------------------+
| The best things in life aren't things. |
+----------------------------------------+
+-------------------------------------------+
| Forget injuries; never forget kindnesses. |
+-------------------------------------------+
+-----------------------------------------------------------+
| Borrow money from a pessimist, They don't expect it back. |
+-----------------------------------------------------------+

最新更新