int,char,string类型互转(C++)

最近写些算法题经常涉及数字字符类型的转换,特地上网查询整理所得,int,char,string三种类型的互转方法,经测试运行正常。
以下是测试整理的代码:

#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdlib>
using namespace std;

int main(){
	int n = 9092;
	char *ch = "6667";
	string str = "8889";

	//(1)int转char 
	char i_c[10];
	sprintf(i_c, "%d", n);
	cout << i_c << endl;
	
	//(2)int转char   头文件:<cstdlib>或<stdlib.h> 
	char i_ch[10];
	_itoa(n, i_ch, 10);    //或 itoa(n, i_ch, 10); 
	cout << i_ch << endl; 
	
	//(3)int转string    头文件:<sstream>和<cstring>|<string.h>
	stringstream ss;
	ss << n;
	string i_str = ss.str();    //或 string i_str; ss >> i_str; 
	cout << i_str << endl;
	
	//(4)char转string    头文件:<cstring>或<string.h>
	string s(ch, ch+strlen(ch));    //或 string s(ch); 
	cout<< s << endl;
	
	//(5)char转int    头文件:<cstdlib>或<stdlib.h> 
	int ch_i = atoi(ch);    //或 long ch_i = atol(ch);或 long long ch_i = atoll(ch);
	cout << ch_i << endl;
	
	//(6)string转char    头文件:<cstring>或<string.h>
	const char *c = str.data();    //或 const char *c=str.c_str(); 
	cout << c << endl;
	
	//(7)string转int    头文件:<sstream>和<cstring>|<string.h>
	stringstream ssy;
	int str_i;
	ssy << str; 
	ssy >> str_i; 
	cout << str_i << endl;
	
	//(8)string转int    头文件:<cstring>和<cstdlib>||<stdlib.h>  
	int in = atoi(str.data());    //或 int in = atoi(str.c_str()); atol/atoll同样可用 
	cout << in << endl;

	return 0;
}

网络整理,如有不妥,望指正!

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值