【问题标题】:Currency Formatting C++货币格式化 C++
【发布时间】:2015-11-29 02:37:43
【问题描述】:

所以我正在尝试创建一个程序,该程序将从用户那里获取一个值并将其转换为货币格式(美元:$)。我似乎快到了,我遇到的唯一问题是,当我输入一个没有小数的值时,它不会用逗号格式化它。我怎样才能改变他的功能,以便无论是否有小数点,它都会格式化。

void dollarFormat(string &currency)
{
    int decimal;
    decimal = currency.find('.'); // Find decimal point
    if (decimal > 3) // Insert commas
    {
        for (int x = decimal - 3; x > 0; x -= 3)
            currency.insert(x, ",");
    }
    currency.insert(0, "$"); // Insert dollar sign
}

【问题讨论】:

    标签: c++ string


    【解决方案1】:

    std::string::npos进行测试:

    void dollarFormat(std::string &currency)
    {
        auto decimal = currency.find('.');  // find decimal point
        if(decimal == std::string::npos)    // no decimal point
            decimal = currency.length();    
        if (decimal > 3) // Insert commas
        {
            for (auto x = decimal - 3; x > 0; x -= 3)
                currency.insert(x, ",");
        }
        currency.insert(0, "$"); // Insert dollar sign
    }
    

    旁注:为了使您的代码可移植,请确保使用std::string::size_type 作为decimal 的类型,而不是int。或者,更好的是,使用auto 类型推导:

    auto decimal = currency.find('.');
    

    【讨论】:

    • 我的教授一直声称使用“auto”关键字是不当行为,应该避免?
    • @ElSpiffy 不不不,再次不。这是强烈推荐使用auto 的示例之一。这并不完全是渎职。问她/他如何在没有auto 的情况下将lambda 分配给变量auto l = [](){std::cout << "use auto";};。并请她/他阅读this
    • 好吧,对于这部分代码,我不会更改它,但每当我有其他课程时,我都会记住它。这位教授也非常反对使用 std:: 方法。这就是为什么我使用命名空间标准;在我的代码顶部。我如何将 std :: string:: npos 更改为我的教授可以接受的格式。
    • @ElSpiffy 我建议您将课程切换到其他讲师 ;) using namespace std; 通常不推荐,因为名称冲突、ADL 问题以及现实世界代码中的许多其他问题。关于std::string::npos,只需使用string::npos(如果你已经是using namespace std;)。
    • 是否可以让这个函数接受一个字符串数组?
    猜你喜欢
    • 2011-09-16
    • 1970-01-01
    • 2016-04-25
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-29
    相关资源
    最近更新 更多