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

时间:2018-09-09 03:33:15

标签: c++ string for-loop border

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

我需要用边框包围“财富”,如下所示,但要使用for循环。

以下是所选择的命运:

一个新的机会等着您,在路的尽头,

早起的鸟儿吃了蠕虫,而第二只老鼠吃了奶酪,

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

人生中最好的东西不是东西

忘记受伤;永远不会忘记仁慈

从悲观主义者那里借钱,他们不希望钱回来

cout << " |=========================================================| \n";
cout << " |" <<fortune[rand_index]<<" | \n";
cout << " |=========================================================| \n";

1 个答案:

答案 0 :(得分:1)

#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. |
+-----------------------------------------------------------+