Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Appending to a string: std::basic_string::append

Choose the `append` overload that matches your source: a whole string, a slice, or a buffer with a known length. Add separators explicitly and preserve embedded nulls.

Version: ISO C++23; implementation support may vary

Syntax

In <string>, for std::basic_string<CharT, Traits, Allocator> dst (C++23):
dst.append(str);                     // whole basic_string
dst.append(str, pos, count = npos);  // slice of a basic_string
dst.append(viewLike);                // whole view
dst.append(viewLike, pos, count = npos); // slice of a view
dst.append(p);                       // null-terminated sequence
dst.append(p, count);                // exactly count elements
dst.append(count, ch);               // count copies of ch
dst.append(first, last);              // valid input-iterator range [first, last)
dst.append({ch1, ch2});               // initializer list
All forms return basic_string&. The notation count = npos denotes a default argument, not an assignment at the call site. append_range(range) is a separate C++23 member.

std::basic_string::append in <string> adds CharT elements to the end of an existing string (std::string is the specialization for char). It returns *this by reference, so calls can be chained. Unlike assign, it does not replace the existing contents, and it does not insert separators automatically. Use push_back(ch) or += ch for one character; push_back returns void.

append(str) copies the whole string. append(str, pos, count) copies up to count elements from source index pos, stopping at the end of the source. Omit count or pass npos to copy through the end. A source pos == size() gives an empty slice; pos > size() throws std::out_of_range. The view-like overloads, available since C++17, work the same way. In C++23, both templates participate in overload resolution only if const T& is implicitly convertible to std::basic_string_view<CharT, Traits>. Only the whole-source template additionally requires that const T& not be implicitly convertible to const CharT*.

append(p) requires a valid null-terminated sequence and copies up to, but not including, the first null. append(p, count) copies exactly count elements, including embedded nulls. It does not clamp the count to the buffer length: check the count against the actual buffer extent, because an invalid range is undefined behavior. Pass both data() and size() to a receiver that accepts length-delimited data.

append(count, ch) adds count copies of ch. You can also pass a valid input-iterator range [first, last) or an initializer list. These append overloads are constexpr since C++20. append_range(range) is a separate C++23 member; check whether your standard library supports it.

An append can invalidate pointers, references, and iterators into the destination string, and thus views of its storage. Obtain fresh ones after mutation. Exceeding max_size() throws std::length_error, and allocation can also fail. If an append call throws, it leaves the destination as it was immediately before that call.

Examples

#include <iostream>
#include <string>
#include <string_view>

int main() {
    const std::string header = "kind=sample";
    const char payload[] = {'A', '\0', 'B'};

    const auto cut = header.find('=');
    if (cut == std::string::npos) {
        return 1;
    }

    std::string message;
    message.append(header, 0, cut)
           .append(1, ':')
           .append(payload, sizeof payload);

    const std::string_view received{message.data(), message.size()};
    if (received != std::string_view{"kind:A\0B", 8}) {
        return 2;
    }

    std::cout << "accepted: " << received.size() << " bytes\n";
}

Result

accepted: 8 bytes

The program checks for the required `=` in the header by comparing the result of `find` with `std::string::npos`. It then appends the slice before `=`, an explicit `:` separator, and three payload bytes. The receiver compares all eight bytes, including the embedded `\0`. Calling `append(payload)` instead of the counted overload would copy only `A`.

Related lessons

  • C++ · Lesson 58 · Advanced · Version: 3

Sources