相关疑难解决方法(0)

如何打印一个空格为千分隔的数字?

我有一个简单的类货币与重载运算符<<.我不知道如何将数字与空格每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)

我感兴趣的是某种最简单的解决方案.

c++

8
推荐指数
2
解决办法
6717
查看次数

如何设置cout语言环境以将逗号作为千位分隔符插入?

给出以下代码:

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)

c++ formatting numbers number-formatting

8
推荐指数
1
解决办法
4477
查看次数

在 C 中打印带有逗号的浮点数

可能的重复:
将 1000000 输出为 1,000,000 等等

我有一个格式为 xxxxxxxx.xx 的浮点变量(例如 11526.99)。我想将其打印为 11,562.99,并带有逗号。C语言中如何插入逗号?

c floating-point floating-point-conversion

0
推荐指数
1
解决办法
2万
查看次数