Help with a function

closed account (9hX8C542)
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

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.
closed account (z05DSL3A)
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()
closed account (9hX8C542)
Thanks both of you, I was having such a hard time, but I'm good now.
Topic archived. No new replies allowed.