Defined in header <cparse/Generator.hh>

static std::string encodeCppString( std::string str ) noexcept;

Encodes str as it would appear inside a C++ string literal (between double quotes).

  • \a, \n, \r, \t, \v — mapped to their two-character escape sequences.
  • \, \', \", \0 — likewise.
  • Any other byte for which std::isprint is false is emitted as a three-digit octal sequence (\000 to \377).
  • All other bytes are copied unchanged.

Static because it does not depend on any generator state.

Parameters

ParameterDescription
strThe bytes to encode. Passed by value; not mutated.

Return value

The encoded string. Length ≥ str.length() — every input byte maps to at least one output byte, and non-printable bytes map to two or three.

Exceptions

noexcept.

Notes

The output is the body of a C++ string literal — the quotes are not added. Wrap with "..." when emitting:

getStream() << '"' << encodeCppString(value) << '"';

The three-digit octal encoding is chosen so the escape does not consume the next byte as part of its digits. For example, the sequence \1a in C++ means the character with octal value 1 followed by the letter a — which is what you want if the input was 0x01 'a'. Using \001a disambiguates unambiguously.

Example

encodeCppString("hello\nworld")
// → "hello\nworld"
// which reads in a C++ source file as: "hello\nworld"

encodeCppString(std::string("\x01\x02\x03"))
// → "\001\002\003"
// which reads as: "\001\002\003"

See also