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 task

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.

Challenge 2

Write std::string format_money(int amount, char currency = '

#39;) that puts the currency sign in front: format_money(800) is "$800" and format_money(50, 'E') is "E50".

Challenge 3

Write std::string bar(int value, int max, int width = 10, char full = '#', char empty = '.') that draws a progress bar width characters long. The number of full characters is value * width / max (rounded down); the rest are empty. A value below 0 counts as 0, and above max counts as max.

Previous: Overloading