设为首页 加入收藏

TOP

C/C++各种数据类型转换汇总
2015-11-10 13:44:51 来源: 作者: 【 】 浏览:6
Tags:C/C 各种 数据 类型 转换 汇总

以下是Windows/Linux系统中常用的C/C++各种数据类型转换汇总:


#include
#include
#include
#include
#include


int main()
{
?// 1--> int to char[]
?int tmp1 = 100;
?char ch1[15];
?sprintf(ch1, "%d", tmp1);
?std::cout<

?// 2--> int to string
?int tmp2 = 111;
?char ch2[15];
?sprintf(ch2, "%d", tmp2);
?std::string str2;
?str2 = std::string(ch2);
?std::cout<

?// 3--> int to enum
?enum enum3 {
? A,
? B
?};
?int tmp3 = 222;
?enum3 val3 = static_cast(tmp3);
?std::cout<

?// 4--> char[] to string
?char arr4[] = "this is a sample";
?std::string str4;
?str4 = std::string(arr4);
?std::cout<

?// 5--> char to int
?char ch5 = '8';
?int val5 = ch5 - '0';// val5 is bounded by 0 to 9
?std::cout<

?// 6--> char[] to int
?char arr6[] = "12345";
?int tmp6;
?sscanf(arr6, "%d", &tmp6);
?std::cout<

?// 7--> char* to int
?char* pch7 = "444";
?int tmp7;
?tmp7 = atoi(pch7);
?std::cout<

?// 8--> char* to float
?char* pch8 = "55.5";
?float tmp8;
?tmp8 = (float)atof(pch8);
?std::cout<

?// 9--> char* to double
?char* pch9 = "66.666";
?double tmp9;
?tmp9 = atof(pch9);
?std::cout<

?// 10--> float to char[]
?float tmp10 = 11.11;
?char ch10[20];
?sprintf(ch10, "%f", tmp10);
?std::cout<

?// 11-> int to char*
?int tmp11 = 777;
?char* pch11;
?char ch11[20];
?sprintf(ch11, "%d", tmp11);
?pch11 = ch11;
?std::cout<

?// 12--> double to char[]
?double tmp12 = 8.888;
?char arr12[20];
?sprintf(arr12, "%f", tmp12);
?std::cout<

?// 13--> char* to string
?char* pch13 = "hello, world";
?std::string str13;
?str13 = std::string(pch13);
?std::cout<

?// 14--> string to char[]
?std::string str14 = "dog, cat";
?char arr14[255];
?strncpy(arr14, str14.c_str(), sizeof(arr14));
?arr14[sizeof(arr14) - 1] = 0;
?std::cout<

?// 15--> string to const char*
?std::string str15 = "ha ha";
?const char* pch15;
?pch15 = str15.c_str();
?std::cout<

?// 16--> float to int
?float ftmp16 = 99.99;
?int tmp16;
?tmp16 = static_cast(ftmp16);// static_cast(ftmp16 + 0.5)
?std::cout<?
?return 0;
}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇回调函数在C/C++中的使用 下一篇二叉树的下一个结点

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: