2015-12-02 94 views
0

我一直在努力讓自己的代碼正常工作。我需要編寫一個程序,使用不超過12位數字的數字,並使用字符串操作將其轉換爲貨幣格式。我覺得我擁有大部分內容,但是我不知道如何讓 - 符號在$符號前面,以及在末尾沒有小數時如何讓逗號生效。C++中的貨幣格式化

這就是:

/* 
    I need a 12 digit maximum double precision number 

     verify that it is a double < 12 digits 
     verify that all digits are numeric with a possible 
     minus sign in the first position t 
     decimal is 2nd or 3rd last digit; 

    convert the number to currency using string manipulation 
     with commas placed at 3 digit intervals counted from the decimal 
     $ in front 
     - in front of $ 
     0 is a positive number 

    Display currency format 
    */ 
#include <iostream> 
#include <string> 


using namespace std; 

void dollarFormat(string &); 

int main() 

{ 
    cout << "Student Name: \t Chad Weireter" << endl 
     << "Student ID:900658044" << endl << endl; 

    string input; 

     cout << "Please enter a number up to 12 digits long." << endl 
      << "The number may be positive or negative" << endl 
      << "and may include fractions (Up to two decimal positions)" << endl 
      << "Sign and decimal dot(.) are not included in the digit count: "; 

     cin >> input; 
     dollarFormat(input); 
     cout << "The currency value is:\t" << input << endl; 

     cin.get(); 
     cin.ignore(); 

} 

void dollarFormat(string &currency) 
{ 
    int dp; 
    dp = currency.find('.'); 
    if (dp > 3) 
    { 
     for (int x = dp - 3; x > 0; x -= 3) 
      currency.insert(x, ","); 
    } 
    currency.insert(0, "$"); 

} 
+0

如果這是作業,請這麼說,以便人們可以幫助,而無需爲你做功課:) – Dan

回答

0

減號

對於減號......你有沒有考慮做你與find('.')做了什麼?

試着做find('-')

如果它的負數是負號,那麼指數的位置是多少?

接下來,如果在該索引處有負號,那麼您應該在0索引處插入美元符號......還是應該將其插入其他位置?

美元符號

當您插入美元符號......你需要做出決定在這裏與控制語句... if正數,然後在索引0插入美元符號(像你這樣已經)... else負面插入索引位置的美元符號... :)