7

向字符串添加多个新行

new lines有没有比我使用的两种方法更吸引人的语法 - 或者重复性更少的语法 - 用于将多个插入字符串中,它们是......


        #1 |   cout << "\n\n\n";
        #2 |   cout << endl << endl << endl;

4

7 回答 7

15

不,没有添加多条空间线的特殊设施。你可以这样做:

std::cout << "\n\n\n\n\n";

或这个

for (int i = 0; i < 5; ++i)
  std::cout << "\n";

或实施您自己的operator*

std::string operator*(std::string const &s, std::size_t n)
{
  std::string r;
  r.reserve(n * s.size());
  for (std::size_t i = 0; i < n; ++i)
    r += s;
  return r;
}

std::cout << (std::string("\n") * 5);

最后,推荐的解决方案:

std::cout << std::string( 5, '\n' );
于 2013-07-08T09:47:25.190 回答
8

您可以编写自己的manipulator,一次可以插入多个换行符。我们称之为mendl(多个endl):

class mendl
{
public:
    explicit mendl(unsigned int i) : n(i) {}
private:
    unsigned int n;

    template <class charT, class Traits>
    friend basic_ostream<charT,Traits>& operator<< (
                                         basic_ostream<charT,Traits>& os,
                                         const mendl& w)
    {
        // the manipulation: insert end-of-line characters and flush
        for (unsigned int i=0; i<w.n; i++)
            os << '\n';
        os.flush();
        return os;
    }
};

用法是:

cout << "dfsdf" << mendl(4);
于 2013-07-08T09:54:42.973 回答
3

您始终可以构建一个包含任意数量的换行符(技术上是 LF)的字符串,如下所示:

cout << "Whatever..." << string(42, '\n');

这将在“Whatever...”之后输出 42 个新行。当然,另一种方法是定义一种新类型(例如mendl称为另一个答案。)

您可以做很多事情,但最简单和最直接的是使用上面的std::string构造函数。但是,您可能需要flush您的流,具体取决于您的用例。

于 2013-07-08T10:36:27.387 回答
3
while(k--)cout<<"\n"; // k is number of lines you wanted
于 2013-07-08T09:48:01.417 回答
1

如果您使用恒定数量的换行符,您可以考虑定义一个常量变量

例如,

const char nl5[] = "\n\n\n\n\n";

您可以在 std::endl 等 cout 的上下文中使用它。

这是整个代码。. .

#include <iostream>

int main()
{
    using namespace std;
    const char nl5[] = "\n\n\n\n\n";
    cout << "ln1" << nl5 << endl;
    cout << "ln2" << nl5 << endl;
}
于 2013-07-08T10:07:12.050 回答
0

不,标准库包含 I 和 O 方法,但数据流中的内容完全取决于您。

endl 做了你要求的一半。调用它两次会得到你想要的。或者,您可以定义一个 endl2x 输出 2 个换行符,或者使用一个参数定义要发出多少个换行符

于 2013-07-08T09:45:02.963 回答
-1

您可以尝试编写一个函数来获取输出流并且没有新行来打印返回输出流

于 2013-07-08T09:49:45.873 回答