Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write 'n' copies of a character to ostream like in python

Tags:

c++

ostream

In python, the following instruction: print 'a'*5 would output aaaaa. How would one write something similar in C++ in conjunction with std::ostreams in order to avoid a for construct?

like image 212
Mihai Bişog Avatar asked Jul 10 '12 20:07

Mihai Bişog


People also ask

How do you repeat a character in times in CPP?

To repeat a string n times, we can use the for loop in C++.

Which of the following functions prints one character at a time?

The getchar() and putchar() Functions This function reads only single character at a time.


1 Answers

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.

like image 73
vitaut Avatar answered Oct 16 '22 02:10

vitaut