C++ 整型与字符串的互转
来源:互联网 发布:幼儿园大班美工作品 编辑:程序博客网 时间:2024/06/07 09:57
C++ 整型与字符串的互转
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.”;
0 0
- C++ 整型与字符串的互转
- 整型与字符串互转
- C++: 整型转字符串
- 字符串转整型与整型转字符串
- [心得]C语言中整型与字符串之间的转换
- 字符串与整型的互换
- c函数之sprintf,sscanf函数使用(字符串与整型互转函数)
- Objective-c 字符串与整型相互转化
- C/C++整型转字符串的几种方法
- Unicode下字符串与整型等的格式转换【转】
- 简单的整型转字符串
- itoa、atoi 整型转字符串、字符串转整型的函数
- JAVA的整型与字符串相互转换
- 【原】整型与字符串的相互转化
- 指针、字符串与整型数据类型的转换
- JAVA的整型与字符串相互转换
- JAVA的整型与字符串相互转换
- JAVA的整型与字符串相互转换
- 使用react-native-vector-icons 库报错 react-native-vector-icons 以及使用方法
- icomoon生成字体图标及使用
- 自己拷贝的目录没有操作权限?
- 魏晋风度与世说新语
- windows 连接上网络,QQ可以使用,但是浏览器无法使用
- C++ 整型与字符串的互转
- 简述安卓框架发展史二(mvp,mvvm)
- 【java实现】算法导论之插入排序递归
- tcpdump简单学习记录
- 【JAVA】线程池的介绍及简单实现
- 窗口过程--自定义绘制窗口(带注释)
- 菜鸟生涯第一次!!!!!!!!!!!!
- c语言结构体数据对齐问题
- 再读《Java编程思想 》