How to write 'n' copies of a character to ostream like in python
Question
In python, the following instruction: print 'a'*5
would output aaaaa
. How would one write something similar in C++ in conjunction with std::ostream
s in order to avoid a for
construct?
Solution
The obvious way would be with fill_n
:
std::fill_n(std::ostream_iterator<char>(std::cout), 5, 'a');
Another possibility would be be to just construct a string:
std::cout << std::string(5, 'a');
OTHER TIPS
Use some tricky way:
os << setw(n) << setfill(c) << "";
Where n is number of char c to write
In C++20 you'll be able to use std::format
to do this:
std::cout << std::format("{:a<5}", "");
Output:
aaaaa
In the meantime you can use the {fmt} library, std::format
is based on. {fmt} also provides the print
function that makes this even easier and more efficient (godbolt):
fmt::print("{:a<5}", "");
Disclaimer: I'm the author of {fmt} and C++20 std::format
.
You can do something like that by overloading the *
operator for std::string. Here is a small example
#include<iostream>
#include<string>
std::string operator*(const std::string &c,int n)
{
std::string str;
for(int i=0;i<n;i++)
str+=c;
return str;
}
int main()
{
std::string str= "foo";
std::cout<< str*5 <<"\n";
}
The standard does not provide any elegant way. But one possibility (my favourite) is to use a proxy object like this
class repeat_char
{
public:
repeat_char(char c, size_t count) : c(c), count(count) {}
friend std::ostream & operator<<(std::ostream & os, repeat_char repeat)
{
while (repeat.count-- > 0)
os << repeat.c;
return os;
}
private:
char c;
size_t count;
};
and then use it this way
std::cout << repeat_char(' ', 5);