views:

471

answers:

6

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
+6  A: 

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. 
Randolpho
A: 

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.

Stacey
-1. Your code is outright wrong for half a dozen reasons. Hell, it won't even compile.
Randolpho
I didn't claim it was right. I saw a familiar problem and remembered how I solved it years ago - but I don't code C++. No reason to be an asshole.
Stacey
Sorry; I'm really not *deliberately* trying to be an asshole, although I can see why you would infer as much from this text medium. The truth is I don't frequently downvote unless something is absolutely wrong and I try to leave a comment as to why. Unfortunately, your code qualifies. I realize you don't code in C++, but to allow that code to stand unchallenged as an answer to this question risks having somebody copy/paste it and shoehorn it until it compiles with their code, and that might lead to a memory leak in some program I might use some day.
Randolpho
I'm really not trying to be insulting, and I apologize for my tone. In fact, I'd be more than happy to discuss the reasons I downvoted in greater detail, if you like.
Randolpho
Then you have a lot of work to do, since 90% of the code on this site doesn't compile verbatim. I've always found stackoverflow to be helpful and informative for discussion and concepts, heaven forbid someone try to give back. I even put in the disclaimer of 'the code is pretty bad' and 'I haven't worked in C++ in a long time'.
Stacey
Don't stress over it. It's a button on a webpage, you don't need to justify it. I'll stick to my areas of experience.
Stacey
Believe me, I understand the desire to give back; it's why I spend so much time here in the first place. But I'd be happy to help you extend your experience in C++, if you like.
Randolpho
It is generally considered poor taste to give built-in operators surprising meanings. Wouldn't giving that member function a name that describes its meaning be better than naming it operator*, which could mean anything? The standard string class doesn't support that operator, and using it on a 0-terminated C-style string would be equivalent to writing `string[0]`. So it would confuse readers to say the least.
janks
@janks: It's bad form to give built-in operators surprising meanings, like using the bit-shift operators for input and output? I know I'm being harsh, but this is one of the things that while "standard" now in C++, is really counter-intuitive when coming from C, and still doesn't make a LOT of sense.
Kevin
Those operators might not have been my first choice either, but the rationale explains why they were chosen, if I recall correctly. But anyway, like it or not, those meanings are supposed to be "unsurprising" now, because they were standardized a dozen years ago, and probably Stroustrup used them long before that. Besides, let's be honest: that shouldn't even break the top 50 on the surprise and confusion list if you're coming from C to C++ ;)
janks
+11  A: 

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>.

janks
+1 for referencing the std library. Too few folks do that these days.
Randolpho
"Concatenation" is also a bad word. There isn't really a word for this, but 'iteration' I think comes closer, since that's really what you have to do to achieve the desired result.
SoapBox
It was 'catenation' when I wrote it.
janks
My dictionary says that one of the definitions of 'concatenation' is 'add by linking or joining so as to form a chain or series'. That strikes me as being an accurate description of this operation.
janks
http://en.wiktionary.org/wiki/concatenate and http://www.merriam-webster.com/dictionary/concatenate
dreamlax
-1 for needlessness. A for loop is, by definition, more readable than using the standard library.
GMan
+2  A: 

You could do this:

std::cout << std::string(7, '*');
Sean
+4  A: 

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;
}
SoapBox
Ah, a meta-programming counter-part to me answer. Most excellent. +1 (Careful, you'll get down votes for being "too clever")
GMan
@GMan So using a built-in std::string constructor is less readable than a for-loop, but this deserves a +1 from you?
joshperry
@josh: If you didn't ever see my answer, and the stupidity expressed by some users on this question (and hence my reply to that stupidity), this won't make sense.
GMan
A: 

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.

webgenius