std::cout to print character N times
Asked Answered
C

3

43

How can I print a character N number of times using std::cout without looping?

Is there a way to move the text cursor back to nullify the effect of std::cout << std::endl;? i.e. to move up a line (say we never printed anything after doing the std::cout << std::endl; operation).

Ciscaucasia answered 25/10, 2011 at 23:46 Comment(1)
C: #14679448Naturalize
D
82
 std::cout << std::string(100, '*') << std::endl;

To move a line up, you have to resort to terminal escapes (assuming that isatty() indicates that you are running on one).

Dzungaria answered 25/10, 2011 at 23:48 Comment(4)
Or not pint the EOL in the first place ??Antler
True, I considered that. In my particular program it seemed easier otherwise.Ciscaucasia
This does not work with Unicode characters.Observance
@Mr.Clear Clearly, unicode wasn't supported (and the little machinery that exists has been deprecated). The best idea I have would probably be fmt::format here : compiler-explorer.com/z/1f98dTn5eDzungaria
H
28
std::cout << std::setfill(the_char) << std::setw(100) << "";
Hate answered 25/10, 2011 at 23:58 Comment(0)
A
0

is there a way to back our way to nullify the effect of cout << endl; i.e. to move up a line(say we never printed anything after doing the cout << endl; operation) Thank you so much!

Use the ternary operator (or an if statement if you refer) ... something like ...

void PrintCharNtimes(char chatToPrint; int numTimes)
{
   std::cout << std::string(numTimes, chatToPrint) << (numTimes > 0) ? std::endl : ;
}
Antler answered 25/10, 2011 at 23:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.