Multiplying a string by an int in C++

user1575615 picture user1575615 · Aug 7, 2012 · Viewed 43.8k times · Source

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

?

Answer

JRG picture JRG · Aug 7, 2012

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

..