How to repeat a string n times in C++

1 Answer

0 votes
#include <iostream>
#include <sstream>
 
std::string repeatstring(std::string str, int n) {
    std::ostringstream os;
     
    for(int i = 0; i < n; i++)
        os << str;
         
    return os.str();
}
 
int main() {
    std::string str = "abc";
    int n = 3;
    
    std::string repeated = repeatstring(str, n);
 
    std::cout << repeated << "\n";
}
 
     
     
/*
run:
     
abcabcabc
      
*/

 



answered Dec 23, 2024 by avibootz
edited Dec 23, 2024 by avibootz

Related questions

1 answer 200 views
3 answers 307 views
1 answer 194 views
1 answer 186 views
186 views asked Feb 1, 2022 by avibootz
3 answers 260 views
1 answer 103 views
1 answer 89 views
89 views asked Dec 23, 2024 by avibootz
...