Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created November 12, 2013 16:43
Show Gist options
  • Save dgodfrey206/7434236 to your computer and use it in GitHub Desktop.
Save dgodfrey206/7434236 to your computer and use it in GitHub Desktop.
How to append a string to an int using the parsing and formatting facets from the IOStreams library.
#include <iostream>
#include <locale>
#include <string>
template <class Facet>
struct erasable_facet : Facet
{
erasable_facet() : Facet(0) { }
~erasable_facet() { }
};
void append_int(std::string& s, int n)
{
erasable_facet<std::num_put<char, std::back_insert_iterator<std::string>>> facet;
std::ios str(nullptr);
facet.put(std::back_inserter(s), str, str.fill(), static_cast<unsigned long>(n));
}
int main()
{
std::string str = "ID: ";
int id = 123;
append_int(str, id);
std::cout << str; // ID: 123
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment