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
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>
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With