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

Dma*_*tig 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";
Run Code Online (Sandbox Code Playgroud)

当这个数字被打成大的东西时,其他一切都变得非常令人头疼.

是否有任何快速简便的方法使其打印"13,653,456"而不是"13653456"就像现在一样(假设当然是输入的内容)?

注意:如果重要,我将其作为Microsoft Visual C++ 2008 Express Edition中的控制台应用程序.

dir*_*tly 16

尝试使用numpunctfacet并重载该do_thousands_sep函数.有一个例子.我还破解了一些只能解决你问题的东西:

#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
} 
Run Code Online (Sandbox Code Playgroud)