今天我尝试了一些C++11 STL的新函数,并遇到了std::to_string
。
这是一组非常好用的函数。以前,为了将double转换为string类型,需要创建一个stringstream对象,这似乎有些过度,现在我们可以像这样做:
std::cout << std::to_string(0.33) << std::endl;
结果是什么?
0.330000
我并不完全满意。有没有办法告诉std:: to_string
去掉尾随零?我在互联网上搜索过,但据我所知该函数只接受一个参数(要转换的值)。在“旧日子”里,使用字符串流可以设置流的宽度,但我不想再进行转换。有人遇到过这个问题/有解决方法吗?一些StackOverflow搜索无果。
(一个C++11 STL参考:http://en.cppreference.com/w/cpp/string/basic_string/to_string)
std::to_string
之后。它返回一个字符串,而不是一个数字,并且其格式似乎很难修改。 - rubenvbto_string
would have to duplicate all that in an equivalent API. Which might not be a terrible idea, but it's not the idea that the committee went with. The reasonto_string
is lovely is that it has no options ;-)可爱、可爱的函数组。对于只进行一次从双精度浮点数到字符串的转换,创建一个stringstream对象似乎有些过度。然而,接下来您会看到它并不是过度——流包含了指定格式的所有基础设施。要得到您想要的内容,to_string
将不得不在一个等效的API中复制所有这些内容。这可能不是个坏主意,但这不是委员会采用的想法。to_string
之所以可爱,是因为它没有选项;-) - Steve Jessop