C/C++ Arena

Step 5 of 5

Default arguments

A parameter can have a default value that's used when the caller leaves the argument out:

#include <iostream>
#include <string>

std::string repeat(const std::string& s, int times = 2, const std::string& sep = " ") {
    std::string out;
    for (int i = 0; i < times; i++) {
        if (i > 0) out += sep;
        out += s;
    }
    return out;
}

int main() {
    std::cout << repeat("go") << "\n";
    std::cout << repeat("go", 3) << "\n";
    std::cout << repeat("go", 3, "-") << "\n";
}
go go
go go go
go-go-go

Rules

Defaults are a lightweight alternative to writing several overloads when the extra parameters are just options with sensible standard values.

Building a string

std::string out; starts empty, and += appends. For padding, std::string(n, c) creates a string of n copies of the character c, which you can then join with +. Always handle the case where nothing needs to be added (the input is already long enough).

Your turn: write std::string pad(const std::string& s, int width, char fill = ' ') that adds fill characters on the left until the string is width long. Strings already that long are returned unchanged.

Previous: Overloading