简体   繁体   中英

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

您可以这样做:

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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM