网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

C++整型与字符串的互转方法-创新互联

这篇文章主要介绍“C++整型与字符串的互转方法”,在日常操作中,相信很多人在C++整型与字符串的互转方法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++整型与字符串的互转方法”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

创新互联公司主营凤山网站建设的网络公司,主营网站建设方案,手机APP定制开发,凤山h5成都微信小程序搭建,凤山网站营销推广欢迎凤山等地区企业咨询

flyfish

字符串转整型

C的方法 cstr是char*或者const char*类型的字符串

int num = atoi(str); int num = strtol(cstr, NULL, 10);

//10 表示进制

C++11的方法

void test1(){  std::string str1 = "1";std::string str2 = "1.5";std::string str3 = "1 with words";int myint1 = std::stoi(str1);int myint2 = std::stoi(str2);int myint3 = std::stoi(str3);std::cout << "std::stoi(\"" << str1 << "\") is " << myint1 << '\n';std::cout << "std::stoi(\"" << str2 << "\") is " << myint2 << '\n';std::cout << "std::stoi(\"" << str3 << "\") is " << myint3 << '\n';}

结果输出

std::stoi(“1”) is 1 std::stoi(“1.5”) is 1 std::stoi(“1 with words”) is 1

//源码参考cplusplus.com

void test2(){ std::string str_dec = "2001, A Space Odyssey"; std::string str_hex = "40c3"; std::string str_bin = "-10010110001"; std::string str_auto = "0x7f"; std::string::size_type sz;  // alias of size_t int i_dec = std::stoi (str_dec,&sz); int i_hex = std::stoi (str_hex,nullptr,16); int i_bin = std::stoi (str_bin,nullptr,2); int i_auto = std::stoi (str_auto,nullptr,0); std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n"; std::cout << str_hex << ": " << i_hex << '\n'; std::cout << str_bin << ": " << i_bin << '\n'; std::cout << str_auto << ": " << i_auto << '\n'; return 0;}

输出

2001, A Space Odyssey: 2001 and [, A Space Odyssey] 40c3: 16579 -10010110001: -1201 0x7f: 127

其他类型 类似

无符号整型

stoul

浮点型

stof

数值转字符串

std::string s; s = std::to_string(1) + ” is int, “;

其他数值类型 类似

s = std::to_string(3.14f) + ” is float.”;

到此,关于“C++整型与字符串的互转方法”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注创新互联网站,小编会继续努力为大家带来更多实用的文章!


网页题目:C++整型与字符串的互转方法-创新互联
URL链接:http://bjjierui.cn/article/phsge.html

其他资讯