In Python, there is a way to multiply a string, for example, "A" * 3
would return "AAA"
. However, this syntax doesn't work in C++, it just gives me an error, invalid operands of types 'const char [2]' and 'int' to binary 'operator*'
. Is there a way to multiply a string like this in C++?

- 95
- 1
- 10
-
In C++, it is probably better to make a function: `string repeat(string s, size_t n) { string result; result.reserve(s.size() * n); while(n--) result += s; return result; }` – Eljay Jun 21 '20 at 13:50
3 Answers
There is no such operator in C++.
But you can write a function that takes a string and a number as argument, and return the repeated string.
std::string
also has a constructor that repeats given character a number of times. This may be useful since you used a string of one character as the example.

- 232,697
- 12
- 197
- 326
You can overload an operator
std::string operator*(const std::string& s, unsigned n)
{
... // your code here
}

- 85,011
- 4
- 57
- 81
-
The operator won't be picked up when the left operand is a string literal, though. – StoryTeller - Unslander Monica Jun 21 '20 at 13:20
-
2Operators overloads whose all arguments are fundamental or standard types are reserved to the standard. – eerorika Jun 21 '20 at 13:21
-
-
Not really... Although you can right one yourself. C++ is a very different beast to Python. It's much more low level and It is not as forgiving.
C++ deals with "real" memory (as it were).
You can't really just say "A" * 3
because before the "A"
simply used 1 byte of memory if you have 3 "A"
's you need 3 bytes. and since C++'s main benefit is in it's ability to allow the user to author It's memory use, C++ won't just create 3 extra bytes.
You can implement your own version of Python's "A" * 3
by using the overload operator (although you would have to use a class type like string) C++ provides But I wouldn't really recommend this.
I'd suggest just using a std::vector
and append the character as many times as you would like.
Also have a think about what you are trying to really do. C++ is all about performance rather than usability. If you are trying to set multiple bytes to a certain value you can use std::memset

- 894
- 6
- 14
-
2
-
-
well the compiler error in the op question already stats it, but "A" is a *null terminated* string, thus "A" is { 'A', '\0' }; thus 2 bytes. I say at least because with utf8 or any other non ascii use, a 'A' may be much larger the a byte. – OznOg Jun 21 '20 at 13:36
-
I was talking more about the fact that you have to create more memory. rather than the exact size.. Thanks – masonCherry Jun 21 '20 at 13:40