gpt4 book ai didi

c++ - 如何在大数字中插入空格以使其更具可读性?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:16:00 24 4
gpt4 key购买 nike

我想到了这个,因为 stackoverflow 上提供的其他示例是用 C# 编写的

string number_fmt(ulong n)
{
// cout << "(" << n << ")" << endl;
char s[128];
sprintf(s, "%lu", n);
string r(s);
reverse(r.begin(), r.end());
int space_inserted = 0;
size_t how_many_spaces = r.length() / 3;

if(r.length() % 3 != 0)
how_many_spaces += 1;

for(int i = 1; i < how_many_spaces; ++i)
{
r.insert(3 * i + space_inserted, " ");
space_inserted += 1;
}
reverse(r.begin(), r.end());

return r;
}

你知道更好的解决方案吗?

最佳答案

我不知道“更好”,但这个版本使用 std::locale 等。

#include <iostream>
#include <locale>
#include <sstream>

template<class Char>
class MyFacet : public std::numpunct<Char> {
public:
std::string do_grouping() const { return "\3"; }
Char do_thousands_sep() const { return ' '; }
};

std::string number_fmt(unsigned long n)
{
std::ostringstream oss;
oss.imbue(std::locale(oss.getloc(), new MyFacet<char>));
oss << n;
return oss.str();
}

int main() {
std::cout << number_fmt(123456789) << "\n";
}


编辑:当然,如果您的最终目标是在 ostream 上打印值,您可以完全跳过将它们存储在 string 中。< p>

#include <iostream>
#include <locale>
#include <sstream>
#include <cwchar>

template <class Char>
class MyFacet : public std::numpunct<Char> {
public:
std::string do_grouping() const { return "\3"; }
Char do_thousands_sep() const { return ' '; }
};

int main(int ac, char **av) {
using std::locale;
using std::cout;

// Show how it works to start with
cout << 123456789 << "\n";

// Switch it to spacey mode
locale oldLoc =
cout.imbue(locale(cout.getloc(), new MyFacet<char>));

// How does it work now?
cout << 456789123 << "\n";

// You probably want to clean up after yourself
cout.imbue(oldLoc);

// Does it still work?
cout << 789123456 << "\n";
}

关于c++ - 如何在大数字中插入空格以使其更具可读性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7257956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com