I want to write myself a function similar to PHP's str_repeat. I want this function to add specified amount of characters at the end of string.
This is a code that does not work (string argument 2 expected!)
void chrrepeat(const char &ch, string &target, const int &count) {
for(int i=0; i<count; i++)
strcat(target, ch);
}
I don't exactly know what language is that (C++?), but you seem to be passing a char to
strcat()instead of a null-terminated string. It's a subtle difference, butstrcatwill happily access further invalid memory positions until a null byte is found.Instead of using
strcat, which is inefficient because it must always search up to the end of the string, you can make a custom function just for this.Here's my implementation in C:
I made it return an empty string for the case that
repeat == 0because that's how it works in PHP, according to the online manual.This code assumes that the target string holds enough space for the repetition to take place. The function's signature should be pretty self explanatory, but here's some sample code that uses it:
This prints: