itoa
/*
int to array
可转八进制、十进制、16进制 等任意进制 */
int source = 15;
char dstEight[3];
char dstTen[3]; // 字符数组长度 至少比数字位数 大1
char dstSixteen[2];
_itoa_s(source, dstEight, 8);
_itoa_s(source, dstTen, 10);
_itoa_s(source, dstSixteen, 16);
cout << "dstEight = " << dstEight << endl; // 17
cout << "dstTen = " << dstTen << endl; // 15
cout << "dstSixTeen = " << dstSixteen << endl; // f
char dstTwo[10];
char dstThree[10];
char dstSeventeen[10];
_itoa_s(source, dstTwo, 2);
_itoa_s(source, dstThree, 3);
_itoa_s(source, dstSeventeen, 17);
cout << "dstTwo = " << dstTwo << endl;
cout << "dstThree = " << dstThree << endl;
cout << "dstSeventeen = " << dstSeventeen << endl;
cout << "----------------------------" << endl << endl;
atoi
/*
array to int
默认转为十进制 */
int dst2 = atoi(dstEight);
cout << "dst2 = " << dst2 << endl;
char source2[10] = { '1','2','3' }; // 123 转为 123
dst2 = atoi(source2);
cout << "source2 atoi = " << dst2 << endl;
char source3[10] = {'1', '4', '3', 'a'}; // 143a 转为 143
dst2 = atoi(source3);
cout << "source3 atoi = " << dst2 << endl;
char source4[10] = { 'b', '1', '4', '3', 'a' }; // b143a 转为 0
dst2 = atoi(source4);
cout << "source4 atoi = " << dst2 << endl;
source4[0] = '+'; // +143a 转为 0
dst2 = atoi(source4);
cout << "source4 atoi = " << dst2 << endl;
source4[0] = '-'; // -143a 转为 -143
dst2 = atoi(source4);
cout << "source4 atoi = " << dst2 << endl;
char source5[100]; // 自己输入值
cout << "请输入字符数组:";
cin >> source5;
dst2 = atoi(source5);
cout << "自己输入source5 atoi = " << dst2 << endl;
cout << "----------------------------" << endl << endl;
/*
应用:十进制转二进制 */
int numTen = 122;
char tmpStr[100];
_itoa_s(numTen, tmpStr, 2);
cout << "tmpStr = " << tmpStr << setw(20) << "tmpStr type = " << typeid(tmpStr).name() << endl; // setw()头文件为<iomanip>
int numTwo = atoi(tmpStr);
cout << "numTwo = " << numTwo << setw(20) << "numTwo type = " << typeid(numTwo).name() << endl;
应用2:int string 互相转化
// int转string to_string
int a = 123;
string res = to_string(a);
cout << "res = begin" << res << "end" << endl;
// string转int
// 先用 c_str() 将string转为静态字符数组
// 再用 atoi 将静态字符数组转为 int
string b = "123456";
const char* stringToInt1;
stringToInt1 = b.c_str();
int stringToInt2;
stringToInt2 = atoi(stringToInt1);
cout << "stringToInt2 = begin:" << stringToInt2 << "end" << endl;