Search code examples
c++stringintegercoutmultiplication

Multiplying a string by an int in C++


What do I have to do so that when I

string s = ".";

If I do

cout << s * 2;

Will it be the same as

cout << "..";

?


Solution

  • No, std::string has no operator *. You can add (char, string) to other string. Look at this http://en.cppreference.com/w/cpp/string/basic_string

    And if you want this behaviour (no advice this) you can use something like this

    #include <iostream>
    #include <string>
    
    template<typename Char, typename Traits, typename Allocator>
    std::basic_string<Char, Traits, Allocator> operator *
    (const std::basic_string<Char, Traits, Allocator> s, size_t n)
    {
       std::basic_string<Char, Traits, Allocator> tmp = s;
       for (size_t i = 0; i < n; ++i)
       {
          tmp += s;
       }
       return tmp;
    }
    
    template<typename Char, typename Traits, typename Allocator>
    std::basic_string<Char, Traits, Allocator> operator *
    (size_t n, const std::basic_string<Char, Traits, Allocator>& s)
    {
       return s * n;
    }
    
    int main()
    {
       std::string s = "a";
       std::cout << s * 5 << std::endl;
       std::cout << 5 * s << std::endl;
       std::wstring ws = L"a";
       std::wcout << ws * 5 << std::endl;
       std::wcout << 5 * ws << std::endl;
    }
    

    http://liveworkspace.org/code/52f7877b88cd0fba4622fab885907313