cout << endlines(x); operator overload for a function

Hi, i wanted to make a function which makes a spacing for a line every time I call cout.

but I am stuck.

my main goal is to use this line of code to work:
 
cout << lines(3);


which creates spaces 3 times

but my code so far is this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
	int lines(unsigned short l = 1)
	{
		l = (l < 1);
		for (int i = 0; i < l; i++)
			cout << endl;
		return l;
	}
	
	ostream& operator <<(ostream& out, int (*f)(unsigned short))
	{
		for (int i = 0; i < f; i++)
			out << '\n';
		return out;
	}


how do I continue from this?
Last edited on
How about
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
struct Lines{
    int l;
};

Lines lines(int l){
    return {l};
}

std::ostream &operator<<(std::ostream &stream, const Lines &l){
    for (int i = l.l; i--;)
        stream << std::endl;
    return stream;
}

std::cout << lines(3);
?
No, it's not working...
Actually, it works now, thanks.
But is there a method of without creating a struct or a class?
The issue is you have an operator of the form "a << b". You need the implementation of this operator to know both 'a' and 'b', so that something like my_file_stream << lines(3) works just as well as std::cout << lines(3), otherwise there isn't a point to using the << operator.
Usually for a custom manipulator you'd just have one class as:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

class lines {
public:
	explicit lines(unsigned l) : line_(l) {}

private:
	unsigned line_ {};

	friend std::ostream& operator<<(std::ostream& os, const lines& li) {
		for (auto l {li.line_}; l--; os << '\n');

		return os;
	}
};

Last edited on
You could say
std::string lines(int n) { return std::string(n, '\n'); }
But it's pretty awful to require a memory allocation just for this.
Last edited on
I have sometimes used std::array<char, n> to return strings from functions without allocating. It's a shame there's no operator<<() overload for it.
Registered users can post here. Sign in or register to post.