2015-11-29 347 views
1

所以我想創建一個程序,將從用戶採取價值並將其轉換爲貨幣格式(美國:$)。我似乎幾乎在那裏,唯一的問題是,當我輸入一個沒有小數的值時,它不會用逗號格式化它。不管小數點有沒有,我怎樣才能改變他的功能,以便格式化它。貨幣格式C++

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 
} 

回答

3

做一個測試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_typedecimal而不是int類型。或者,甚至更好,使用auto類型推演:

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

我的教授一直聲稱使用「自動」關鍵字是醫療事故,應當避免? –

+1

@ElSpiffy否否否再次否。這是強烈推薦使用'auto'的例子之一。這並非完全不當。詢問她/他如何將一個lambda賦值給一個變量,'auto l = [](){std :: cout <<「use auto」;};'without'auto'。並要求她/他閱讀[this](http://herbsutter.com/elements-of-modern-c-style/)。 – vsoftco

+0

那麼,對於這部分代碼我不會改變它,但是當我有另一個類時,我會記住它。這位教授也非常反對使用std ::方法。所以爲什麼我使用命名空間std;在我的代碼的頂部。如何將std :: string :: npos更改爲我的教授可以使用的格式。 –