Help with a function
Apr 3, 2019 at 9:48pm Apr 3, 2019 at 9:48pm UTC
So I need to write a function that is described like this:
std::string capitalize(const std::string& str);
/// Returns a copy of the string centered in a string of length 'width'. /// Padding is done using the specified 'fillchar' (default is an ASCII space).
/// The original string is returned if 'width' is less than or equal to the /// string's length.
/// @example center("C++ is fun", 20, '*') becomes " *****C++ is fun*****"
Header and parameters need to stay the same.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
std::string center(const std::string& str, size_t width,
char fillchar)
{
int size1 = 0;
int size2 = 0;
int strLength = str.length();
string newOutput = "" ;
if (strLength < width)
{
size1 = strLength - width;
size2 = size1/2;
newOutput.append(size2, fillchar);
newOutput = newOutput + str;
newOutput.append(size2, fillchar);
return newOutput;
}//if for string length
else
return str;
}//function to center
When I try to compile I get the error:
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_M_replace_aux
Thanks for your time
Apr 3, 2019 at 10:14pm Apr 3, 2019 at 10:14pm UTC
size2 , when calculated on line 12, is a negative number.
Using the string::append function with a negative number as the first parameter is a bad idea.
Apr 3, 2019 at 10:42pm Apr 3, 2019 at 10:42pm UTC
You could also look at creating the new string the correct size prefilled with the fillchar and then replace the middle section with the old string.
Look at the std::string constructor and std::string.replace()
Apr 3, 2019 at 11:22pm Apr 3, 2019 at 11:22pm UTC
Thanks both of you, I was having such a hard time, but I'm good now.
Topic archived. No new replies allowed.