Multiply char by integer (c++)

大城市里の小女人 提交于 2020-01-10 19:41:14

问题


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

回答1:


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




回答2:


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. 



回答3:


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



回答4:


You could do this:

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



回答5:


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.




回答6:


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

}



来源:https://stackoverflow.com/questions/2596953/multiply-char-by-integer-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!