各种基本类型与string的转换
时间:2014-03-05 18:08:37
收藏:0
阅读:541
基于C++11标准
如果你用的编译器是基于最新的C++11标准,那么这个问题就变的很简单,因为<string>中已经封装好了对应的转换方法:
标准库中定义了to_string(val);可以将其它类型转换为string。还定义了一组stoi(s,p,b)、stol(s,p,b)、stod(s,p,b)等函数,可以函数,可以分别转化成int、long、double等.
VS2013下编译通过
void testTypeConvert() { //int --> string int i = 5; string s = to_string(i); cout << s << endl; //double --> string double d = 3.14; cout << to_string(d) << endl; //long --> string long l = 123234567; cout << to_string(l) << endl; //char --> string char c = ‘a‘; cout << to_string(c) << endl; //自动转换成int类型的参数 //char --> string string cStr; cStr += c; cout << cStr << endl; s = "123.257"; //string --> int; cout << stoi(s) << endl; //string --> int cout << stol(s) << endl; //string --> float cout << stof(s) << endl; //string --> doubel cout << stod(s) << endl; }
结果如下:
5
3.140000
123234567
97
a
123
123
123.257
123.257
C++11标准之前
C++11标准之前没有提供相应的方法可以调用,就得自己写转换方法了,代码如下:
从其它类型转换为string,定义一个模板类的方法。
从string转换为其它类型,定义多个重载函数。
VS2010下编译通过
#include <strstream> template<class T> string convertToString(const T val) { string s; std::strstream ss; ss << val; ss >> s; return s; } int convertStringToInt(const string &s) { int val; std::strstream ss; ss << s; ss >> val; return val; } double convertStringToDouble(const string &s) { double val; std::strstream ss; ss << s; ss >> val; return val; } long convertStringToLong(const string &s) { long val; std::strstream ss; ss << s; ss >> val; return val; } void testConvert() { //convert other type to string cout << "convert other type to string:" << endl; string s = convertToString(44.5); cout << s << endl; int ii = 125; cout << convertToString(ii) << endl; double dd = 3.1415926; cout << convertToString(dd) << endl; //convert from string to other type cout << "convert from string to other type:" << endl; int i = convertStringToInt("12.5"); cout << i << endl; double d = convertStringToDouble("12.5"); cout << d << endl; long l = convertStringToLong("1234567"); cout << l << endl; }
结果如下:
convert other type to string:
44.5
125
3.14159
convert from string to other type:
12
12.5
1234567
各种基本类型与string的转换,布布扣,bubuko.com
原文:http://blog.csdn.net/luoweifu/article/details/20493177
评论(0)