1:将int ,long ,long long,flaot,double,long double等转化为string
方法一:to_string()函数运用
这个函数的用法其实也挺简单就是在括号内加上你想转化的数字然后赋给一个string类型的变量就行了
例如:想要将int a = 100转化为string b = "100"可以这么做
string b = to_string(100)
注意:c++11以上(包括11)才能使用
方法二:可以说是万能方法用stringstream这里要注意要添加#include <sstream>
用法如下:先构造一个字符串流stringstream 然后将要转化的数字输出到该字符流中最后在通过str()函数获取内容在用cout输出
例如:........
stringstream os;//构造一个字符串流
int i = 11;//要转化的数字
os << i;//数字输出到该字符流
cout << os.str() ;
2:将string转化为int ,long ,long long,flaot,double,long double等
这里简绍两种方法
方法一(简单的一种):用标准库函数atoi(->int)atof(->float)atol(->long),,itoa(->char[],不推荐使用),
但是注意这几个函数中的参数是接受的c风格的char数组所以要进行转化c_str()
例如:......................
string a = "100";
int b = atoi(a.c_str());//完成转化
cout << b + 1;//101
注意要添加#include <cstdlib>
方法二:用上面的sstream中的stringstream
例如:.............
stringstream is("123");//构造字符串流,流的内容初始化为“123”的字符串
int i;
is >> i;//从is流中读入一个int整数存入i中