这里我列举几种相互转换的方法
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 !
原文链接: https://www.cnblogs.com/blog-zhangchongen/p/14948108.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/205482
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!