C++之字符串和其他类型之间的相互转换

C++常用函数

1.字符串 --> 整形的函数

1.1 stoi()

int stoi(const string &str,size_t* idx=0,int base=10);

注意:

1.可以直接将字符串转换为int类型

2.idx和base可以不设置

3..stoi()存在安全检查,会检查输入是否越界,越界会报错runtime error!

1.2 stringstream【重点】

功能:

可以实现任意两个类型之间的转换

头文件:

#include<sstream>

源代码:

template<typename out_type, typename in_value>
out_type convert(const in_value & t){
	stringstream stream;
	stream<<t;//向流中传值
	out_type result;//这里存储转换结果
   stream>>result;//向result中写入值
   return result;
}

优点:

1.不会涉及到溢出问题---底层使用的是:string类型

2.溢出会自动截断

简单使用:

#include <iostream>
#include <sstream>
using namespace std;
int main(int argv,char** argc) {
 string a = "123";
 stringstream x;
 x<<a;  // 输入数据
 int t;
 x>>t;  // 转换成其他类型数据
 cout<<t;
 return 0;
}
posted @ 2022-07-30 15:21  nanfengnan  阅读(171)  评论(0编辑  收藏  举报