2009-04-26 111 views
6

這裏有一個小菜,所以最好假設我在任何答案中都不知道。在C++中插入和從整數中刪除逗號

我一直在寫一個小應用程序,它運行良好,但可讀性是我的數字的噩夢。

本質上,我想要做的就是在屏幕上顯示的數字中添加逗號,以便於閱讀。有沒有一個快速簡單的方法來做到這一點?我一直在使用stringstream來獲取我的數字(我不確定爲什麼這個建議在這一點上,這只是在我通過的教程中建議的),比如(裁剪掉不相關的位) :

#include <iostream> 
#include <string> 
#include <sstream> 
using namespace std; 

int items; 
string stringcheck; 

... 

    cout << "Enter how many items you have: "; 
     getline (cin, stringcheck); 
     stringstream(stringcheck) >> items; 

... 

    cout << "\nYou have " << items << " items.\n"; 

當該號碼的類型是什麼大,除一切就變得頗爲頭疼閱讀。

有沒有什麼快捷的方法可以讓它打印出「13,653,456」而不是像現在這樣的「13653456」?(假設這是當然的輸入)?

注意:如果重要,我將它作爲Microsoft Visual C++ 2008 Express Edition中的控制檯應用程序。

+0

而不是使用「\ n」,你可以使用std :: endl;輸入換行符。 – Tom 2009-04-26 18:06:05

+0

@Tom:不,除非他希望這個流也被沖洗掉(同時爲沖洗花費一點時間處罰)。 – dirkgently 2009-04-26 18:18:16

回答

16

嘗試numpunct方面並超載do_thousands_sep函數。有一個example。我也砍了一些東西,只是解決您的問題:

#include <locale> 
#include <iostream> 

class my_numpunct: public std::numpunct<char> { 
    std::string do_grouping() const { return "\3"; } 
}; 

int main() { 
    std::locale nl(std::locale(), new my_numpunct); 
    std::cout.imbue(nl); 
    std::cout << 1000000 << "\n"; // does not use thousands' separators 
    std::cout.imbue(std::locale()); 
    std::cout << 1000000 << "\n"; // uses thousands' separators 
}