本文已参与「新人创作礼」活动,一起开启掘金创作之路。
这里我列举几种相互转换的方法
字符串到整数
string型字符串到整数
调用sstream中的stringstream
注意头文件#include #include 下面看代码:
string str21 = "1234";
int m;
stringstream ss;
ss << str21;
ss >> m;//字符串转换成整数
cout << m<<endl;
调用函数to_string
int m=2344;
string str23 =to_string(m);
cout << str23<<endl;
char型字符串到整数
调用atoi函数
/*字符串转换成整数atoi函数*/
char str10[10] = "1234";
int n = atoi(str10);
cout << n << endl;
整数到字符串
整数到string型字符串
使用stringstream
int m=12345;
string str22;
ss << m;
ss >> str22;
cout << str22 << endl;
整数到char型字符串
使用_itoa_s
首先不同环境下的这个函数不太一样,如果报错了根据错误修改
/*整数转换成字符串_itoa_s函数*/
int n=3242;
char str11[10];
_itoa_s(n,str11,10);
cout << str11 << endl;
完整测试代码
#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 !