c++字符串和整数转换方法(总结)

这里我列举几种相互转换的方法

1、字符串到整数

1.1 string型字符串到整数

1.1.1 调用sstream中的stringstream

注意头文件#include
#include
下面看代码:

	string str21 = "1234";
	int m;
	stringstream ss;
	ss << str21;
	ss >> m;//字符串转换成整数
	cout << m<<endl;

1.1.2 调用函数to_string

	int m=2344;
	string str23 =to_string(m);
	cout << str23<<endl;

1.2 char型字符串到整数

1.2.1调用atoi函数

/*字符串转换成整数atoi函数*/
	char str10[10] = "1234";
	int n = atoi(str10);
	cout << n << endl;

2、 整数到字符串

2.1 整数到string型字符串

2.1.1 使用stringstream

	int m=12345;
	string str22;
	ss << m;
	ss >> str22;
	cout << str22 << endl;

2.2 整数到char型字符串

2.2.1 使用_itoa_s

首先不同环境下的这个函数不太一样,如果报错了根据错误修改

/*整数转换成字符串_itoa_s函数*/
	int n=3242;
	char str11[10];
	_itoa_s(n,str11,10);
	cout << str11 << endl;

3、完整测试代码

#include<iostream>
#include<sstream>
#include<string>

using namespace std;

int main()
{
	/*字符串转换成整数atoi函数*/
	char str10[10] = "1234";
	int n = atoi(str10);
	cout << n << endl;

	/*整数转换成字符串_itoa_s函数*/
	char str11[10];
	_itoa_s(n,str11,10);
	cout << str11 << endl;


	/*另一种方法*/
	string str21 = "1234";
	int m;
	stringstream ss;
	ss << str21;
	ss >> m;//字符串转换成整数
	cout << m<<endl;

	string str22;
	ss << m;
	ss >> str22;
	cout << str22 << endl;

	string str23 =to_string(m);
	cout << str23<<endl;

	

	return 0;
}

如果有疑惑欢迎进群交流:1142983793 !

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值