开发者

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


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. 


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;
}


You could do this:

std::cout << std::string(7, '*');


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.


//include iostream and string libraries

using namespace std;

int main()
{

    for (int Count = 1; Count <= 10; Count++)
    {
        cout << string(Count, '+') << endl;
    }

    for (int Count = 10; Count >= 0; Count--)
    {
        cout << string(Count, '+') << endl;
    }


return 0;

}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜