0

Repeating a string

How can I repeat a string n times in c++?

10th Apr 2024, 6:54 AM
Hossam Eldeen
Hossam Eldeen - avatar
12 odpowiedzi
+ 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
10th Apr 2024, 1:19 PM
Bob_Li
Bob_Li - avatar
+ 5
If you mean printing it several times, then put the cout inside a for loop.
10th Apr 2024, 7:04 AM
Tibor Santa
Tibor Santa - avatar
+ 4
Hossam Eldeen another option is using auto for (auto _(2); _--;) {} https://sololearn.com/compiler-playground/cWFv8b4lIk0P/?ref=app
10th Apr 2024, 5:36 PM
BroFar
BroFar - avatar
+ 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.
11th Apr 2024, 6:59 AM
Abiye Gebresilassie Enzo Emmanuel
Abiye Gebresilassie Enzo Emmanuel - avatar
+ 1
Thank you
10th Apr 2024, 7:06 AM
Hossam Eldeen
Hossam Eldeen - avatar
+ 1
Bob_Li thank you very much
10th Apr 2024, 2:06 PM
Hossam Eldeen
Hossam Eldeen - avatar
+ 1
BroFar that for loop is new to me.😎 I am stealing that...😁
10th Apr 2024, 5:52 PM
Bob_Li
Bob_Li - avatar
+ 1
BroFar thank you it's very simple and useful
10th Apr 2024, 7:09 PM
Hossam Eldeen
Hossam Eldeen - avatar
+ 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; }
11th Apr 2024, 2:58 AM
Bob_Li
Bob_Li - avatar
+ 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.
11th Apr 2024, 3:21 AM
BroFar
BroFar - avatar
+ 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);_--;){}
11th Apr 2024, 3:31 AM
Bob_Li
Bob_Li - avatar
+ 1
Gracias
12th Apr 2024, 4:39 AM
Alejandro Leon
Alejandro Leon - avatar