C++中string char* int 之间的转换方法

#include<iostream>
#include<sstream>
using namespace std;
 	int main() {
	long a = INT_MAX+1;
	string b = "22222abc33333";
	char* c = "33333abc444";
	string d;
	cout << to_string(a) << endl;//to_string用于将int转换为string,超出int范围不报错,但只显示int值
	cout << stoi(b) << endl;//stoi在转换string类时,如果遇到字符,不再转换后续整型及字符
	cout << atoi(c) << endl;//atoi只可以用于const char*(char*可以自动转换为const char *)
	stringstream ss;
	ss << a;
	ss >> d;
	cout << d << endl;
	cout << stoi(b) << endl;
}

对应的结果如下:
在这里插入图片描述
总结:
1、字符串(包括char*,const char*,string)与int的转换可以使用stringstream。
2、char*到int用可以用atoi,string到int可以用stoi,注意!如果字符串里存在非int数据(比如小数点、字符等),后续数据(即使是int)也不再转换。

string char* char[]之间的转换:
https://blog.csdn.net/jojozym/article/details/104792257

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值