Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

?

like image 944
user1575615 Avatar asked Aug 07 '12 09:08

user1575615


2 Answers

std::string has a constructor of the form

std::string(size_type count, char c);

that will repeat the character. For example

#include <iostream>

int main() {
   std::string stuff(2, '.');
   std::cout << stuff << std::endl;
   return 0;
}

will output

..
like image 108
JRG Avatar answered Nov 06 '22 04:11

JRG


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

like image 35
ForEveR Avatar answered Nov 06 '22 03:11

ForEveR