C++ STL 字符串转其他类型 其他类型转字符串

#ifndef EX18_H_INCLUDED
#define EX18_H_INCLUDED
#include <iostream>
#include <string>
#include <sstream>
//模板函数,将字符串转换成其他数据类型
template <class T>T fromString(const std::string& s){
    std::istringstream is(s);
    T t;
    is>>t;
    return t;
}
//模板函数,将其他数据类型转换成字符串
template <class T>std::string toString(const T&t){
    std::ostringstream s;
    s<<t;
    return s.str();
}
#endif // EX18_H_INCLUDED
#include "Ex18.h"
#include <iostream>
#include <complex>
using namespace std;

int main()
{
    int i=1234;
    float j=567.34;
    complex<float> c(2.5,4.1);
    cout<<"i==\""<<toString(i)<<"\""<<endl;   //将数字转换为字符串
    cout<<"i==\""<<toString(j)<<"\""<<endl;
    cout<<"i==\""<<toString(c)<<"\""<<endl;
    i=fromString<int>(string("1234"));
    j=fromString<float>(string("567.34"));
    c=fromString< complex<float> >(string("(2.5,4.1)"));
    cout<<"i==\""<<i<<"\""<<endl;  //将字符串转换为数字
    cout<<"i==\""<<j<<"\""<<endl;
    cout<<"i==\""<<c<<"\""<<endl;
    return 0;
}


猜你喜欢

转载自blog.csdn.net/ibelievesunshine/article/details/80201477
今日推荐