代码:
#include <iostream>
#include <string>
#include <cstdlib>
/*
时间:2018.06.28
类型转换
*/
#define CHAR_TO_INT(x) int((x) - '0')
void Show(char *p);
void ShowString(std::string &p);
int StrToInt(const std::string &p);
int main()
{
using namespace std;
/* 初始化 */
char temp;
char t[10] = {0};
char * p = NULL;
string str = "";
int mInt = 0;
double mDouble = 0.0;
__int64 mInt64 = 0;
/* string 转 char* */
str = "123456";
p = (char *)str.c_str();
Show(p);
str = "789";
p = (char *)str.data();
Show(p);
str = "456";
str.copy(p,str.length(),0);
Show(p);
str = "";
/* char* 转 string */
p = "123";
str = p;
ShowString(str);
p = NULL;
/* string 转 char[] */
str = "456789";
//str.data()取得就是str的首地址
//注意数组的大小 不要溢出影响到地址映射的其他数据
strcpy(t,str.data());
Show(t);
memset(t,0,sizeof(t));
str = "";
str = "123456";
int i = 0;
for (; i < str.length(); i++)
{
t[i] = str[i];
}
if ( i < sizeof(t))
{
t[i+1] = '\0'; //字符串赋值数组 会有‘\0’结尾
}
memset(t,0,sizeof(t));
str = "";
/* string 转 int double int64 */
str = "123";
mInt = atoi(str.c_str());
mDouble = atof(str.c_str());
mInt64 = _atoi64(str.c_str());
printf(" int = %d, double = %f, int64 = %llu\n",mInt,mDouble,mInt64);
str = "";
str = "456";
mInt = stoi(str);
mDouble = stod(str);
/*
string封装的一些字符串与数的转换函数
to_string(val) 把val转换成string
stoi(str,pos,b) 把字符串str从p开始转换成int
stol(str,pos,b) long
stoul(str,pos,b) unsigned long
stoll(str,pos,b) long long
stoull(str,pos,b) unsigned long long
stof(str,pos) float
stod(str,pos) double
stold(str,pos) long double
*/
printf(" int = %d, double = %f, int64 = %llu\n",mInt,mDouble,mInt64);
str = "";
//可以自己写个算法转换
str = "123456789";
mInt = StrToInt(str);
cout <<"StrToInt(str) = "<< mInt << endl;
str.clear();
/* char 转 int */
temp = '9';
cout << " CHAR_TO_INT = "<< CHAR_TO_INT(temp) << endl;
/************* FINALLY *******/
delete p;
p = NULL;
system("pause");
return 0;
}
void Show(char *p)
{
std::cout << " char * = ";
while (*p != NULL)
{
std::cout << *p << " ";
p++;
}
std::cout << "\n";
}
void ShowString(std::string &p)
{
std::cout << "string = "<< p.c_str() << std::endl;
}
int StrToInt(const std::string &p)
{
int i = 0,val = 0,strLenth = p.length();
//判断是否为负数
if ( p[0] == ' - ' )
i = 1 ;
//循环单个字符赋值
while (i < strLenth)
{
//p[i] - ' 0 ' = 对应数字大小的ASCII
val = val * 10 + ( int )(p[i] - '0');
i ++ ;
}
if (p[ 0 ] == ' - ' )
val *= - 1 ;
return val;
}
输出:
//
char * = 1 2 3 4 5 6
char * = 7 8 9
char * = 4 5 6
string = 123
char * = 4 5 6 7 8 9
int = 123, double = 123.000000, int64 = 123
int = 456, double = 456.000000, int64 = 123
StrToInt(str) = 123456789
CHAR_TO_INT = 9
请按任意键继续…
//