Multiply char by integer (c++)

后端 未结 6 662
甜味超标
甜味超标 2020-12-31 16:03

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 d

相关标签:
6条回答
  • 2020-12-31 16:21

    You could do this:

    std::cout << std::string(7, '*');
    
    0 讨论(0)
  • 2020-12-31 16:23

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

    0 讨论(0)
  • 2020-12-31 16:29

    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. 
    
    0 讨论(0)
  • 2020-12-31 16:32

    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;
    }
    
    0 讨论(0)
  • 2020-12-31 16:39

    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.

    0 讨论(0)
  • 2020-12-31 16:39
    //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 讨论(0)
提交回复
热议问题