In python, the following instruction: print \'a\'*5
would output aaaaa
. How would one write something similar in C++ in conjunction with std:
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 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');