What I am trying to do here is write a function repeat that accepts a string and a positive integer n and returns that string repeated n times. Thus repeat("fho", 3) would return the string “hohoho”. However, the below test program runs but doesn’t display the result or hang. I tried to add a system pause but that didn’t help. What am I missing?
#include <string>
#include <iostream>
std::string repeat( const std::string &word, int times ) {
std::string result ;
result.reserve(times*word.length()); // avoid repeated reallocation
for ( int a = 0 ; a < times ; a++ )
result += word ;
return result ;
}
int main( ) {
std::cout << repeat( "Ha" , 5 ) << std::endl ;
return 0 ;
}
Your code seems to work, but personally I think I’d write it a bit differently: