一、int转string
1.如果你用的编译器是基于最新的C++11标准,那么string和其他类型转换问题就变的很简单,因为中已经封装好了对应的转换方法:
标准库中定义了to_string(val);可以将其它类型转换为string。
string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val)
2.采用sstream中定义的字符串流对象来实现
ostringstream os; //构造一个输出字符串流,流内容为空
int i = 12;
os << i; //向输出字符串流中输出int整数i的内容
cout << os.str() << endl; //利用字符串流的str函数获取流中的内容
二、string转int
1.C++11还定义了一组stoi(s,p,b)、stol(s,p,b)、stod(s,p,b)等转换函数,可以分别转化成int、long、double等. 在头文件<string>
stoi(s,p,b);stol(s,p,b);stoul(s,p,b);stoll(s,p,b);stoull(s,p,b);返回s的起始子串(表示整数内容的字符串)的数值,返回值的类型分别为:int、long、unsigned long、long long、unsigned long long.其中b表示转换所用的基数,默认为10(表示十进制).p是size_t的指针,用来保存s中第一个非数值字符的下标,p默认为0,即函数不返回下标.
stof(s, p); stod(s, p); stold(s, p); 返回s的起始子串(表示浮点数内容)的数值,返回值的类型分别是float、double、long double.参数p的作用与整数转换函数中的一样。
非数字开头的会抛出std::invalid_argument异常。
#include <iostream>
#include <string>
int main()
{
std::string a = "a123asd";
int i = std::stoi(a);//std::invalid_argument异常
std::cout << i << std::endl;
getchar();
return 0;
}
2.2.采用标准库中atoi函数,对于其他类型也都有相应的标准库函数,比如浮点型atof(),long型atol()等等.在头文件<cstdlib>
string s = "12";
int a = atoi(s.c_str());
3.采用sstream头文件中定义的字符串流对象来实现转换
istringstream is("12"); //构造输入字符串流,流的内容初始化为“12”的字符串
int i;
is >> i; //从is流中读入一个int整数存入i中