我有一个简单的类货币与重载运算符<<.我不知道如何将数字与空格每3位数分开,所以看起来像是:"1 234 567 ISK".
#include <cstdlib>
#include <iostream>
using namespace std;
class Currency
{
int val;
char curr[4];
public:
Currency(int _val, const char * _curr)
{
val = _val;
strcpy(curr, _curr);
}
friend ostream & operator<< (ostream & out, const Currency & c);
};
ostream & operator<< (ostream & out, const Currency & c)
{
out << c.val<< " " << c.curr;
return out;
}
int main(int argc, char *argv[])
{
Currency c(2354123, "ISK");
cout << c;
}
Run Code Online (Sandbox Code Playgroud)
我感兴趣的是某种最简单的解决方案.
给出以下代码:
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) 可能的重复:
将 1000000 输出为 1,000,000 等等
我有一个格式为 xxxxxxxx.xx 的浮点变量(例如 11526.99)。我想将其打印为 11,562.99,并带有逗号。C语言中如何插入逗号?