CKTIS / C++
std::basic_string constructor: repeat a character
Build a string containing exactly `count` copies of `ch`. Use parentheses to select the fill overload rather than the initializer-list overload.
Version: ISO C++23; implementation support may vary
Syntax
// Constructor declaration inside std::basic_string<CharT, Traits, Allocator> (<string>)
constexpr basic_string(size_type count, CharT ch,
const Allocator& alloc = Allocator());
// Direct initialization of the std::string specialization
std::string padding(4, '0');The std::basic_string count/character constructor in <string> creates a new string that owns count copies of ch. std::string is an alias for std::basic_string<char>, so ch is a char in that case. After successful construction, size() is count: zero gives an empty string, and copies of \0 count as elements just like any other character. The optional third argument is the allocator; omitting it uses Allocator().
Use parentheses: std::string(4, '0') produces "0000". In contrast, std::string{4, '0'} selects the std::initializer_list<char> overload and stores two elements: a char with value 4 and the character '0'. The separate (const CharT*, size_type) overload copies elements from the supplied range instead of repeating one character.
The fill overload has been constexpr since C++20, but not every call can be a constant expression. size_type is unsigned. Reject negative input before conversion and impose a practical limit on untrusted counts. A count greater than max_size() causes std::length_error; allocation can fail even below that limit.
For text already known to contain only digits, check length < width first. Only in that branch, construct width - length zeros and prepend them. Otherwise, keep the suffix with substr(length - width). The check prevents unsigned wraparound in either subtraction; the example does not validate that its input contains only digits.
Examples
#include <iostream>
#include <string>
std::string last_four_or_pad(const std::string& digits)
{
constexpr std::string::size_type width = 4;
const auto length = digits.size();
if (length < width) {
return std::string(width - length, '0') + digits;
}
return digits.substr(length - width);
}
int main()
{
std::cout << last_four_or_pad("7") << '\n';
std::cout << last_four_or_pad("123456") << '\n';
std::cout << last_four_or_pad("1234") << '\n';
}Result
0007 3456 1234
`7` needs three zeros, `123456` keeps its last four digits, and `1234` is unchanged.
Related lessons
- C++ · Lesson 53 · Advanced · Version: 3