c++ string类型和int类型的相互转换

一.string类型转换成int类型

方法一:使用atoi()函数

#include<bits/stdc++.h>
using namespace std;
int main(){
	string str="123";
	cout<<str<<"    str的类型为"<<typeid(str).name()<<endl;//输出Ss表示string类型
	//atoi的参数类型为(const char *nptr)而string是一个类,所以需要获取str的首地址即str.c_str()
	int num=atoi(str.c_str()); 
	cout<<num<<"    num的类型为"<<typeid(num).name()<<endl;//输出i表示int类型 
}

用devc++的typeid(num).name()输出是i,vs2017输出的是int,不同编译器这个函数输出可能不同啦。
还有一些类似的函数:
long atol(const char *nptr);把字符串转换成长整型数
double atof(const char *nptr);把字符串转换成浮点数
long int strtol(const char *str, char **endptr, int base);把参数 str 所指向的字符串根据给定的 base 转换为一个长整数

方法二:通过stringstream类转化

#include<bits/stdc++.h>
using namespace std;
int main() {
	stringstream sstream;
	string str="123";
	int num;
	cout<<"str="<<str<<"    str的类型为"<<typeid(str).name()<<endl;//输出Ss表示string类型
	sstream<<str;// 将string类型的值放入字符串流中
	sstream>>num;//将sstream中的第一条数据输出到num中 
	cout<<"num="<<num<<"    num的类型为"<<typeid(num).name()<<endl;//输出i表示int类型
}

二.int类型转换成string类型

方法一:使用to_string()函数

#include<bits/stdc++.h>
using namespace std;
int main() {
	int num=123;
	string str=to_string(num);
	cout<<"num="<<num<<"    num的类型为"<<typeid(num).name()<<endl;//输出i表示int类型
	cout<<"str="<<str<<"    str的类型为"<<typeid(str).name()<<endl;//输出Ss表示string类型
}

to_string(x)函数有多个重载,只要x是内置数值类型就可以。

方法二:通过stringstream类转化

#include<bits/stdc++.h>
using namespace std;
int main() {
	stringstream sstream;
	string str;
	int num=123;
	cout<<"num="<<num<<"    num的类型为"<<typeid(num).name()<<endl;//输出i表示int类型
	sstream<<num;// 将num类型的值放入字符串流中
	sstream>>str;//将sstream中的第一条数据输出到str中 
	cout<<"str="<<str<<"    str的类型为"<<typeid(str).name()<<endl;//输出Ss表示string类型
}

方法三:使用itoa()函数
函数原型:char * itoa(int value ,char *string ,int radix);
第一个参数是要转换的数字
第二个参数是要写入转换结果的目标字符串(字符型数组)
第三个参数是转移数字时所用的基数(进制)⭐(可以用来做进制转换)
返回值:指向string这个字符串的指针

#include<bits/stdc++.h>
using namespace std;
int main() {
	int num=123;
	char strc[100];
	string str=itoa(num,strc,10);//返回的是指向strc的指针,直接存进string类型即可
	cout<<"num="<<num<<"    num的类型为"<<typeid(num).name()<<endl;//输出i表示int类型
	cout<<"str="<<str<<"    str的类型为"<<typeid(str).name()<<endl;//输出Ss表示string类型
}

其他类似的函数:
litoa() 将长整型值转换为字符串
ultoa() 将无符号 长整型值转换为字符串

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值