在c ++中插入和删除整数中的逗号

时间:2009-04-26 17:41:17

标签: 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中的控制台应用程序。

1 个答案:

答案 0 :(得分: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
} 
相关问题