C++ Basics: Round-Trip a String with Spaces and Quotes
Use std::quoted with string streams to preserve spaces, embedded quotes, and backslashes.
Prepare a scratch directory
Tested on Linux x86_64 with GCC 14.2.0. Install a C++20-capable compiler and standard-library development headers, with g++ on PATH. You also need Bash, a text editor, and the mktemp, rm, and rmdir utilities. No third-party library is required.
Keep the same terminal open. Stop if setup fails, before saving the source:
start_directory="$PWD"
work_directory="$(mktemp -d)" || exit 1
cd -- "$work_directory" || exit 1Run the example
Save this as quoted-string-round-trip-demo.cpp:
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
int main()
{
const std::string original = "say \"hello\" at C:\\work";
std::ostringstream output;
output << std::quoted(original);
std::cout << "Encoded: " << output.str() << '\n';
std::istringstream input(output.str());
std::string restored;
if (!(input >> std::quoted(restored))) {
std::cerr << "Decode failed\n";
return 1;
}
std::cout << "Restored: " << restored << '\n';
std::cout << "Equal: " << std::boolalpha << (restored == original) << '\n';
}Compile and run it. The program runs only after compilation succeeds:
g++ -std=c++20 -Wall -Wextra -Werror -pedantic quoted-string-round-trip-demo.cpp -o quoted-string-round-trip-demo &&
./quoted-string-round-trip-demoObserved output:
Encoded: "say \"hello\" at C:\\work"
Restored: say "hello" at C:\work
Equal: trueRead the result
The encoded form surrounds the value with double quotes and escapes internal quotes and backslashes. Reading with the matching manipulator restores the original string, including spaces. The equality check verifies the round trip instead of relying only on how the text looks.
Apply it carefully
std::quoted is a stream convention, not a general JSON, CSV, or shell encoder. Its default backslash escaping does not implement all of those formats. If input does not start with the chosen delimiter, extraction falls back to ordinary string extraction. Check stream status and validate trailing content separately when parsing a whole record. Do not treat successful extraction alone as proof of a valid external format.
The C++ working draft describes the relevant rules. This example builds in C++20 mode; the current working draft also documents later additions.
Clean up
Remove only the source and executable created here, then return to the starting directory:
rm -- quoted-string-round-trip-demo.cpp quoted-string-round-trip-demo
cd -- "$start_directory" || exit 1
rmdir -- "$work_directory"
unset start_directory work_directoryIf the directory is not empty, inspect its remaining contents before removing anything else.
Acknowledgements
This post was created with assistance from AI.