1、string转换成int
#include<iostream>
#include<sstream>
#include<string>
using namespace std;
int main()
{
string s = "1234567";
int res = 0;
//method 1
/*
int len = s.size();
for (int i = 0; i < len; i++)
{
res = res * 10 + s[i] - '0';
}
*/
//method 2
//res = atoi(s.c_str());
//method 3 stringstream 很强大
stringstream ss;
ss << s;
ss >> res;
//method 4
res=stoi(s);
cout << res << endl;
system("pause");
return 0;
}
2、int转换成string
int main()
{
int number = 1345;
string res;
//method 1
//res = to_string(number);
//method 2
stringstream ss;
ss << number;
res = ss.str();
cout << res << endl;
system("pause");
return 0;
}
介绍两个函数:itoa() atoi()
a)itoa函数
功能:把一整数转换为字符串
函数原型:char *itoa(int value, char *string, int radix);
头文件:#include<stdlib.h>
参数:
value:待转化的整数
radix:是基数的意思,即先将value转化为radix进制的数,范围介于2-36,比如10表示10进制,16表示16进制。
string:保存转换后得到的字符串
b)atoi函数
功能:把字符串转换成整型
函数原型:int atoi(const char *nptr);
头文件: #include<stdlib.h>
3、int转char
#include<iostream>
#include<sstream>
#include<string>
#include<stdio.h>
using namespace std;
int main()
{
int i = 1234;
char res[10];
//method 1
//sprintf_s(res,"%d",i);//sprintf是C函数,vs2017做了更新(担心内存越界等),使用sprintf_s,功能是一样的
//method 2
_itoa_s(i, res, 10); //与sprintf_s一样的原因
//method3
cout << res << endl;
system("pause");
return 0;
}
自写函数,实现itoa的功能:
//method 1
#include<iostream>
#include<sstream>
#include<string>
#include<stdio.h>
using namespace std;
char *myitoa(int num, char *str, int radix)
{
/* 索引表 */
char index[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
unsigned unum; /* 中间变量 */
int i = 0, j, k;
/* 确定unum的值 */
if (radix == 10 && num<0) /* 十进制负数 */
{
unum = (unsigned)-num;
str[i++] = '-';
}
else unum = (unsigned)num; /* 其它情况 */
/* 逆序 */
do
{
str[i++] = index[unum % (unsigned)radix];
unum /= radix;
} while (unum);
str[i] = '\0';
cout << "i=" << i << endl;
/* 转换 */
if (str[0] == '-') k = 1; /* 十进制负数 */
else k = 0;
/* 将原来的“/2”改为“/2.0”,保证当num在16~255之间,radix等于16时,也能得到正确结果 */
char temp;
if (k == 1)
{
for (j = k; j <= (i - 1) / 2.0; j++)
{
temp = str[j];
str[j] = str[i - j];
str[i - j] = temp;
}
}
else if (k == 0)
{
for (j = k; j <= (i - k - 1) / 2.0; j++)
{
temp = str[j];
str[j] = str[i - j - 1];
str[i - j - 1] = temp;
}
}
return str;
}
int main()
{
int number = -1234567;
char string[25];
myitoa(number, string, 10);
printf("integer = %d string = %s\n", number, string);
system("pause");
return 0;
}
4、char转int
#include<iostream>
#include<string>
#include<stdio.h>
#include<stack>
using namespace std;
int main()
{
char num[] = "-12345";
//method 1
/*
int len = sizeof(num);
int res = 0;
bool flag = 0;
int i = 0;
if (num[0] == '-')
{
flag = 1;
i++;
}
else if (num[0] == '+')
{
flag = 0;
i++;
}
for (; i < len-1; i++)
{
res = res * 10 + num[i] - '0';
}
if (flag == true)
res = -res;
*/
//method 2
int res = atoi(num);
cout << res << endl;
system("pause");
return 0;
}
5、char转string
string s(char *);
6、string转char
char *p = string.c_str();