许多JAVA爱好者批评STL在std::string模板中没有包含一些十分有用的函数。之所以将这些函数排斥在外是因为你可以很容易自己编写它们。例如,你可以这样实现一个将所有数据类型转换为字符串型的to_string函数:
template< class T>
inline std::string to_string( const T & Value)
{
std::stringstream streamOut;
streamOut << Value;
return streamOut.str( );
}
// 对原数据类型为string类型的特殊处理
template< >
inline std::string to_string( const std::string & Value)
{
return Value;
}
该函数对所有C++内有数据类型均适用。对支持“<<”运算符的类同样适用。
当然,实现与to_string功能相反的函数也是容易的。下面一小段代码将解释这一点。
template< class T>
inline T from_string( const std::string & ToConvert)
{
std::stringstream streamIn( ToConvert);
T ReturnValue = T( );
streamIn >> ReturnValue;
return ReturnValue;
}
from_string函数将字符串转化为某一类型。例如,它可以将字符串转化为数据。如果输入有效,本函数将转换并返回它。另外,该函数返回指定的类型的默认值,T()为默认的构造函数。还有,它适用与任何C++内有的数据类型,对任何默认构造函数实现了“>>”操作符的类也同样适用。
注意from_string函数假定你转换的字符串中仅有一个值,任何多余的值都将被忽略。如果字符串有多值并且都是你需要的,请勿使用form_string函数,你可以从流中(直接)读取它们。
下面的例子说明了如何使用上述的两个函数:
int n = 4;
std::string str = to_string( n);
// "4"
long l = 534587;
str = to_string( l);
// "534587"
n = from_string< int>( "a");
// 0
int nTest = from_string< int>( "5744");
// 5744
int nTest2 = from_string< int>( "57y4");
// 57
int nTest3 = from_string< int>( "5743 65");
// 5743; 65 ignored !!!
return 0;