Also diese Antwort ist die C++ Destillation von Antwort Jerry Coffin auf diese Frage: Cross Platform Support for sprintf's Format '-Flag
template <typename T>
enable_if_t<is_integral_v<remove_reference_t<T>>, string> poscommafmt(T N, const numpunct<char>& fmt_info) {
string result = to_string(N % 10);
const auto group = fmt_info.grouping();
auto places = 0U;
for (auto posn = '\1'; 0 != (N /= 10); ++posn, result = to_string(N % 10) + result) {
if (group[places] == posn) {
if (places + 1U < size(group)) {
++places;
}
posn = '\0';
result = fmt_info.thousands_sep() + result;
}
}
return result;
}
template <typename T>
enable_if_t<is_integral_v<remove_reference_t<T>>, string> commafmt(const T N, const numpunct<char>& fmt_info) {
return N < 0 ? '-' + poscommafmt(-N, fmt_info) : poscommafmt(N, fmt_info);
}
dies aus dem Kompliment Negation Problem leidet natürlich die gleich 2.
Dies profitiert sicherlich von C++ string
Speicherverwaltung, sondern auch von der Fähigkeit, eine bestimmte numpunct<char>
übergeben, die nicht das aktuelle Gebietsschema sein muss. Zum Beispiel, ob oder nicht cout.getloc() == locale("en-US")
können Sie anrufen: commafmt(foo, use_facet<numpunct<char>>(locale("en-US")))
Live Example
So haben Sie eine Nummer zu tausend getrennten Zeichenfolge oder eine Zeichenfolge zu einem Tausend getrennten Zeichenfolge konvertieren mögen oder brauchen Sie nur ausgeben, dass das so? – NathanOliver
@NathanOliver Ja, und natürlich konnte ich sie manuell einfügen. Aber das wird nicht locale angemessen sein :( –
Kannst du nicht [this] (https://stackoverflow.com/questions/17530408/print-integer-with-tausend-and-millions-separator) dann verwenden? Du brauchst eigentlich eine Schnur. – NathanOliver