C++ 整型与字符串的互转方式
flyfish
字符串转整型
C的方法cstr是char*或者constchar*类型的字符串
intnum=atoi(str);
intnum=strtol(cstr,NULL,10);
//10表示进制
C++11的方法
voidtest1() { std::stringstr1="1"; std::stringstr2="1.5"; std::stringstr3="1withwords"; intmyint1=std::stoi(str1); intmyint2=std::stoi(str2); intmyint3=std::stoi(str3); std::cout<<"std::stoi(\""<结果输出
std::stoi(“1”)is1 std::stoi(“1.5”)is1 std::stoi(“1withwords”)is1//源码参考cplusplus.com
voidtest2() { std::stringstr_dec="2001,ASpaceOdyssey"; std::stringstr_hex="40c3"; std::stringstr_bin="-10010110001"; std::stringstr_auto="0x7f"; std::string::size_typesz;//aliasofsize_t inti_dec=std::stoi(str_dec,&sz); inti_hex=std::stoi(str_hex,nullptr,16); inti_bin=std::stoi(str_bin,nullptr,2); inti_auto=std::stoi(str_auto,nullptr,0); std::cout<输出
2001,ASpaceOdyssey:2001and[,ASpaceOdyssey] 40c3:16579 -10010110001:-1201 0x7f:127其他类型类似
无符号整型
stoul
浮点型
stof
数值转字符串
std::strings;
s=std::to_string(1)+”isint,“;其他数值类型类似
s=std::to_string(3.14f)+”isfloat.”;
以上这篇C++整型与字符串的互转方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。