首页 > 技术文章 > c++字符串和整数转换方法(总结)

blog-zhangchongen 2020-11-27 22:01 原文

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

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 !

推荐阅读