我想编写一个方法,它将采用一个整数并返回一个std::string用逗号格式化的整数.
示例声明:
std::string FormatWithCommas(long value);
Run Code Online (Sandbox Code Playgroud)
用法示例:
std::string result = FormatWithCommas(7800);
std::string result2 = FormatWithCommas(5100100);
std::string result3 = FormatWithCommas(201234567890);
// result = "7,800"
// result2 = "5,100,100"
// result3 = "201,234,567,890"
Run Code Online (Sandbox Code Playgroud)
将数字格式化为string逗号的C++方式是什么?
(奖金也将用于处理double.)
给出以下代码:
cout << 1000;
Run Code Online (Sandbox Code Playgroud)
我想要以下输出:
1,000
Run Code Online (Sandbox Code Playgroud)
这可以使用std :: locale和cout.imbue()函数来完成,但我担心我可能会错过这里的一步.你能发现它吗?我正在复制当前的语言环境,并添加了一个千位分隔符,但逗号永远不会出现在我的输出中.
template<typename T> class ThousandsSeparator : public numpunct<T> {
public:
ThousandsSeparator(T Separator) : m_Separator(Separator) {}
protected:
T do_thousands_sep() const {
return m_Separator;
}
private:
T m_Separator;
}
main() {
cout.imbue(locale(cout.getloc(), new ThousandsSeparator<char>(',')));
cout << 1000;
}
Run Code Online (Sandbox Code Playgroud)