0

Repeat string in c++

is there any way to repeat string in c++. I want to write a function that takes two argument as input, one as string and other integer and then print the string the number of times the integer provided in argument. for eg. repeatstring("hello",3); output hellohellohello

20th Jun 2017, 2:38 AM
Sonu Kumar Singh
Sonu Kumar Singh - avatar
7 Antworten
+ 13
printThis("Hello", 3) ..... while(numPrinted < numEntered) { cout << stringEntered; numPrinted++; }
20th Jun 2017, 3:17 AM
jay
jay - avatar
+ 8
//just for one character. char f; cin>>f; cout<<string(10,f)<<endl;
20th Jun 2017, 6:50 AM
Enas Emad
Enas Emad - avatar
+ 6
a loop is what you want
20th Jun 2017, 2:58 AM
jay
jay - avatar
+ 5
#include <iostream> #include <string.h> using namespace std; void repeatString(string,int); int main() { int n; string str; getline(cin,str); cin>>n; repeatString(str,n); return 0; } void repeatString(string str, int n) { for(int i=0;i<n;i++) { cout<<str; } }
20th Jun 2017, 9:31 AM
Sachin Artani
Sachin Artani - avatar
0
agree but how? we can't do something like this in c++ (cout<<str*i) where str is string and i is number
20th Jun 2017, 3:00 AM
Sonu Kumar Singh
Sonu Kumar Singh - avatar
0
#include <iostream> #include <string> using namespace std; string repeat(string s, int n) { string s1 = s; for (int i=1; i<n;i++) s += s1; // Concatinating strings return s; } // Driver code int main() { string s = "Print \n"; int n; cin>>n; string s1 = s; for (int i=1; i<n;i++) s += s1; cout << s << endl;; return 0; }
1st Dec 2020, 11:32 PM
Françesko Kalemaj
Françesko Kalemaj - avatar
0
#include <iostream> std::string operator* (std::string& self, unsigned int num) { std::string buff = ""; for(unsigned int i = 0; i < num; i++) { buff.append(self); } return buff; } int main() { std::string input; std::cin >> input; //multiplying string //(you can change this number) std::cout << input * 5; }
15th Apr 2021, 6:33 PM
Sergey
Sergey - avatar