我通过谷歌找到了以下代码。它几乎实现了我的要求,但它没有提供像C类型格式字符串中'%.*f'一样指定精度的方法。而且,它最多只能提供5个小数位。我是否必须坚持使用C字符串和snprintf?
#include <string>
#include <sstream>
#include <iostream>
template <class T>
std::string to_string(T t, std::ios_base & (*f)(std::ios_base&))
{
std::ostringstream oss;
oss << f << t;
return oss.str();
}
int main()
{
std::cout<<to_string<double>(3.1415926535897931, std::dec)<<std::endl;
return 0;
}
std::cout
,但 pi 在to_string<long>(long t)
中被格式化。此外,由于你将 pi 作为long
传递,它变成了3L
。 - MSalters