如何打印一个带有空格的数字作为千分隔符? [英] How to print a number with a space as thousand separator?
本文介绍了如何打印一个带有空格的数字作为千分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的类Currency with重载运算符<<我不知道如何可以分隔数字与空格每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&运算符<< (ostream& out,const Currency& c);
};
ostream&运算符<< (ostream& out,const Currency& c)
{
out< c.val < < ;
return out;
}
int main(int argc,char * argv [])
{
Currency c(2354123,ISK);
cout<< C;对我有用[0]丢个板砖[0]引用|举报|编辑删除管理回复次数: p>
解决方案这可以使用facets
struct myseps:numpunct< char> {
/ *使用空格作为分隔符* /
char do_thousands_sep()const {return''; }
/ *数字每个3位组合* /
string do_grouping()const {return\3; }
};
int main(){
std :: cout.imbue(std :: locale(std :: locale(),new myseps));
std :: cout<< 10000; // 10 000
}
或者,您可以编写自己的循环
void printGrouped(ostream& out,int n){
if(n< 0){
out ;& - ;
返回printGrouped(out,-n);
}
if(n <1000){
out< n;
} else {
printGrouped(out,n / 1000);
out<< < setw(3)<< setfill('0')<< (n%1000);
}
}
ostream&运算符<< (ostream& out,const Currency& c){
printGrouped(out,c.val);
out<< < ;
return out;
}
I've got a simple class Currency with overloaded operator<<. I don't know how can i separate the number with spaces every 3 digits, so it looks like: "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;
}
What interests me, is somehow the easiest solution for this particular situation.
解决方案 This can be done with facets
struct myseps : numpunct<char> {
/* use space as separator */
char do_thousands_sep() const { return ' '; }
/* digits are grouped by 3 digits each */
string do_grouping() const { return "\3"; }
};
int main() {
std::cout.imbue(std::locale(std::locale(), new myseps));
std::cout << 10000; // 10 000
}
Alternatively, you may code your own loop
void printGrouped(ostream &out, int n) {
if(n < 0) {
out << "-";
return printGrouped(out, -n);
}
if(n < 1000) {
out << n;
} else {
printGrouped(out, n / 1000);
out << " " << setw(3) << setfill('0') << (n % 1000);
}
}
ostream & operator<< (ostream & out, const Currency & c) {
printGrouped(out, c.val);
out << " " << c.curr;
return out;
}
这篇关于如何打印一个带有空格的数字作为千分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文