Connecting Tech Pros Worldwide Forums | Help | Site Map

printout of characters

Geoff Jones
Guest
 
Posts: n/a
#1: Jul 23 '05
Hiya

Can anybody remind me of the format command, or otherwise, to print a number
of the same character e.g. if I wanted to printout 20 *'s

********************
then I'm sure there is an inbuilt command, without using a loop, that will
do it.

Can anybody remind me of what it is?

Ta

Geoff



Mike Wahler
Guest
 
Posts: n/a
#2: Jul 23 '05

re: printout of characters



"Geoff Jones" <nodamnspam@email.com> wrote in message
news:41e012e0$0$11839$cc9e4d1f@news.dial.pipex.com ...[color=blue]
> Hiya
>
> Can anybody remind me of the format command,[/color]

C++ does not have 'commands'.
[color=blue]
>or otherwise, to print a number
> of the same character e.g. if I wanted to printout 20 *'s
>
> ********************
> then I'm sure there is an inbuilt command, without using a loop, that will
> do it.
>
> Can anybody remind me of what it is?[/color]

There are a virtually unlimited number of possible ways.
I'd do it like this:

#include <iostream>
#include <string>

int main()
{
const std::string::size_type count(20);
char c('*');

std::cout << std::string(count, c) << '\n';
return 0;
}

-Mike


Jerry Coffin
Guest
 
Posts: n/a
#3: Jul 23 '05

re: printout of characters


> Can anybody remind me of the format command, or otherwise, to print a
number[color=blue]
> of the same character e.g. if I wanted to printout 20 *'s[/color]
[color=blue]
> ********************[/color]

There are quite a few possibilities. One reasonably clean one would be:

std::fill_n(std::ostream_iterator<char>(std::cout) , 20, '*');

If you prefer to use only the native abilities of iostreams, you could
use:

std::cout << std::setfill('*') << std::setw(20) << ' ';

but this prints an extra space at the end of the line -- if that's all
that's going to go on the line, you might prefer:

std::cout << std::setfill('*') << std::setw(20) << '\n';

or, if you don't want a new line, something like:

std::cout << std::setfill('*') << std::setw(19) << '*';

At least in theory, the versions using iostreams capabilities might be
marginally more efficient, but given that this is producing output on a
stream, it's hard to imagine how it would make any real difference, so
at least to me, fill_n seems the obvious choice.

--
Later,
Jerry.

The universe is a figment of its own imagination.

Closed Thread


Similar C / C++ bytes