0
Repeating a string
How can I repeat a string n times in c++?
12 Answers
+ 2
you can define a repeat function, or use a more complicated set of operator overloads (that I found on StackOverflow).
https://stackoverflow.com/questions/33572768/possible-to-overload-operator-to-multiple-an-int-and-a-char
https://sololearn.com/compiler-playground/cewC3toWF9N8/?ref=app
+ 5
If you mean printing it several times, then put the cout inside a for loop.
+ 4
Hossam Eldeen another option is using auto
for (auto _(2); _--;) {}
https://sololearn.com/compiler-playground/cWFv8b4lIk0P/?ref=app
+ 3
In C++, you can repeat a string `n` times using various methods. One simple way is to use a loop to concatenate the string `n` times. Here's an example:
https://sololearn.com/compiler-playground/cl7pH1od7NlR/?ref=app
In this example, the `repeatString` function takes a string `s` and an integer `n` as arguments and returns a new string consisting of `s` repeated `n` times.
+ 1
Thank you
+ 1
Bob_Li thank you very much
+ 1
BroFar
that for loop is new to me.đ I am stealing that...đ
+ 1
BroFar thank you it's very simple and useful
+ 1
BroFar
I did some experimentation and came up with an even shorter form. Plus a default value if nothing is inputted.
#include <iostream>
using namespace std;
int main() {
int n=1;
cin >> n;
for (; n--;){ cout<<"this\n";}
return 0;
}
+ 1
Bob_Li just quick thought if leaving the auto keyword as an auto initializer out if this is a truly a good thing since auto was first recognized back in 2011 and has respectfully been used in the various versions of cpp since.
Yes , with the absence of auto _(); or auto _{}; may be something done here ... But best practice may say otherwise under real world activities and software.
+ 1
BroFar but in the for loop, you are basically recasting int n to auto _(n).
if it is a one time use of n, this can be skipped and just directly use n.
But if n is going to be reused later on, yes, I agree that auto _(n); is the wiser choice.
Auto keyword is nice. But it is additional compiler work . If you really want to micro-optimize, you can also use for(int _(n);_--;){}
+ 1
Gracias