Skip to content

Instantly share code, notes, and snippets.

@myl7
Created December 26, 2021 12:17
Show Gist options
  • Save myl7/2371770485bf9d3b6919dc71df56c4da to your computer and use it in GitHub Desktop.
Save myl7/2371770485bf9d3b6919dc71df56c4da to your computer and use it in GitHub Desktop.
Append a char into std::stringstream in C++ is hard
#include <sstream>
#include <string>
#include <cstdio>
int main() {
std::stringstream a;
a << "0"; // const char *
printf("%s\n", a.str().c_str()); // 0, expected
std::stringstream b;
b << std::string("0"); // std::string
printf("%s\n", b.str().c_str()); // 0, expected, std::string seems duplicated
std::stringstream c;
c << '0'; // char
printf("%s\n", c.str().c_str()); // 0, expected
std::stringstream d;
d << 0; // int
printf("%s\n", d.str().c_str()); // 0, int is parsed literally, other than as ASCII code, we know but may ignore or misundertand
std::stringstream e;
e << 0x00; // int
printf("%s\n", e.str().c_str()); // 0, hex is still int
std::stringstream f;
f << '\x00'; // char
printf("%s\n", f.str().c_str()); // None, char(0) works
std::stringstream g;
g << char(0); // char
printf("%s\n", g.str().c_str()); // None, more explicitly
std::stringstream h;
h << static_cast<char>(0); // char
printf("%s\n", h.str().c_str()); // None, modern C++ version
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment