Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply char by integer (c++)

Is it possible to multiply a char by an int?

For example, I am trying to make a graph, with *'s for each time a number occurs.

So something like, but this doesn't work

char star = "*";
int num = 7;

cout << star * num //to output 7 stars
like image 300
dubya Avatar asked Apr 08 '10 01:04

dubya


2 Answers

I wouldn't call that operation "multiplication", that's just confusing. Concatenation is a better word.

In any case, the C++ standard string class, named std::string, has a constructor that's perfect for you.

string ( size_t n, char c );

Content is initialized as a string formed by a repetition of character c, n times.

So you can go like this:

char star = '*';  
int num = 7;
std::cout << std::string(num, star) << std::endl;  

Make sure to include the relevant header, <string>.

like image 59
janks Avatar answered Sep 18 '22 15:09

janks


the way you're doing it will do a numeric multiplication of the binary representation of the '*' character against the number 7 and output the resulting number.

What you want to do (based on your c++ code comment) is this:

char star = '*';
int num = 7;
for(int i=0; i<num; i++)
{
    cout << star;
}// outputs 7 stars. 
like image 33
Randolpho Avatar answered Sep 19 '22 15:09

Randolpho