本工具可以在字符串与其他基本类型之间进行转换
/************************************
文件:str_tools.h
作者:hntzy
描述:本类是一个字符转换工具
*************************************/
#ifndef __STR__TOOLS__H__
#define __STR__TOOLS__H__
#include <string>
#include <strstream>
class StrTool{
private:
StrTool(); //不能构造实例
public:
template <typename T>
static T strToOthers(const std::string& str); //字符转其他类型
template <typename T>
static std::string othersToStr(T t); //其他类型转字符串
};
template <typename T>
T StrTool::strToOthers(const std::string& str){
std::istrstream istrstrm(str.data());
T t;
istrstrm >> t;
return t;
}
template <typename T>
std::string StrTool::othersToStr(T t){
std::ostrstream ostrstrm;
ostrstrm << t << std::ends; //ends不能少,表示结束
return ostrstrm.str();
}
#endif
测试
#include <iostream>
#include "str_tools.h"
int main(){
long long a = 10L;
std::string str = StrTool::othersToStr<long long>(a);
std::cout << str;
long double d = StrTool::strToOthers<long double>("123123123.14");
std::cout.precision(20);
std::cout << std::endl << d;
getchar();
return 0;
}