在C++中插入和从整数中删除逗号
问题描述:
这里有一个小菜,所以最好假设我在任何答案中都不知道。在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中的控制台应用程序。
答
尝试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
}
而不是使用“\ n”,你可以使用std :: endl;输入换行符。 – Tom 2009-04-26 18:06:05
@Tom:不,除非他希望这个流也被冲洗掉(同时为冲洗花费一点时间处罚)。 – dirkgently 2009-04-26 18:18:16