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
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
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.
You might try looking into operator overloading if you're going to be doing this a lot in your code.
Something like this... ( I haven't coded C++ in a long, long time. So this won't compile )
char String::operator*(int total) {
string strOutput = new string();
for(int i = 0; i < total; i++ )
strOutput += *this;
return strOutput;
}
Though that code is pretty bad. I haven't worked with C++ in a long time. Take a look at http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html.
Essentially you'll build an operator that takes a left hand and right hand, and returns a type. You can put your logic in here to make a re-usable instance of what you're wanting.
Though it seems I get insulted just for proposing ideas, so I won't bother with it any further.
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>
.
GMan's over-eningeering of this problem inspired me to do some template meta-programming to further over-engineer it.
#include <iostream>
template<int c, char ch>
class repeater {
enum { Count = c, Char = ch };
friend std::ostream &operator << (std::ostream &os, const repeater &r) {
return os << (char)repeater::Char << repeater<repeater::Count-1,repeater::Char>();
}
};
template<char ch>
class repeater<0, ch> {
enum { Char = ch };
friend std::ostream &operator << (std::ostream &os, const repeater &r) {
return os;
}
};
main() {
std::cout << "test" << std::endl;
std::cout << "8 r = " << repeater<8,'r'>() << std::endl;
}
The statement should be:
char star = "*";
(star * num) will multiply the ASCII value of '*' with the value stored in num
To output '*' n times, follow the ideas poured in by others.
Hope this helps.