2013-10-20 67 views
-1

我想讓用戶輸入爲一個C字符串「xxx,xxx,xxx.xx」(x's是數字)。所以如果我輸入「343,111,222.00」,那麼輸出將完全相同。所以問題是,這是如何完成的?我想我想要做的是,如果用戶放置「123456」,那麼輸出自動輸入「123,456.00」。任何建議/提示/批評表示讚賞。C++輸入逗號和十進制

#include <stdio.h> 
    #include <string.h> 
    #include <iostream> 
    #include <string> 
int main() { 

    using namespace std; 
char myStr[256];  
    char tempStr[256]; 
    double sum = 0; //Adding sum soon. 
    int decreaseDist; 

    cout << "Enter Any integers "; 
    cin.getline(myStr,256); 
    cout << endl; 

    int finalCount = 0; 

int i; 
    long distToDot = tempStr[256] - 3; 


for(i=0; myStr[i] != '\0'; i++) { 
      putchar(myStr[i]); 
      decreaseDist = distToDot = i; 

    if(i !=0 && decreaseDist > 0 && decreaseDist % 3== 0) 
        { 
        tempStr[finalCount++] = ','; 
      } 

      tempStr[finalCount++] = myStr[i]; 
    } 
    tempStr[finalCount] = '\0'; 

    return 0; 
} 
+0

看一看http://stackoverflow.com/questions/7276826/c-format-number-with - 可以看看你怎麼能做到這樣的事情:) – yamafontes

+0

好的,將檢查出來,謝謝。 – Christian

回答

0

看來,你的問題有兩個部分:

  1. 如何總是與恰好兩位小數的十進制數。在回答這個問題是建立在流使用fixed格式和精度爲2:

    std::cout << std::setprecision(2) << std::fixed; 
    
  2. 問題的其他部分似乎問如何創建千位分隔符。在回答這個問題是使用std::locale用合適的std::numpunct<char>方面,如:

    struct numpunct 
        : std::numpunct<char> { 
        std::string do_grouping() const { return "\3"; } 
    }; 
    int main() { 
        std::cout.imbue(std::locale(std::locale(), new numpunct)); 
        std::cout << double(123456) << '\n'; 
    } 
    
+0

感謝您的回覆。我有很多要學習的。感謝您對每個代碼的解釋。 – Christian

相關問題