c++ 字符串和数字相互转化
2016-03-07 16:24
666 查看
在C++11中string 类中有stoi、stod、stof、stol和stoll等函数分别是把字符串转化为int、double、float、long和long、long型。
而数字转字符串则用to_string
用法举例如下:
另外,stoi还可以指定向2、8、10、16进制转化:
而数字转字符串则用to_string
用法举例如下:
#include <iostream> // std::cout #include <string> // std::string, std::stod int main () { std::string str_bin = "2456" int i_bin = std::stoi (str_bin); std::string s=std::to_string(i_bin); }
另外,stoi还可以指定向2、8、10、16进制转化:
// stoi example #include <iostream> // std::cout #include <string> // std::string, std::stoi int main () { 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; }
相关文章推荐
- C++中的单例模式
- 2016.3.7 16.14复习篇之三(蓝桥杯恶补)
- Cpp--处理字符串的自定义类
- C语言中改变字体颜色和背景的方法
- C++继承和多态
- C/C++服务器架构机制设计总结
- C语言实现简单的SMTP发送邮件
- C++ 如何定义动态二维数组?
- c++工厂模式和c++工厂方法
- C语言深度剖析-----函数
- c语言中cJson的使用
- C语言学习之结构体(一)
- protobuf:c++示例
- C++文件操作详解(ifstream、ofstream、fstream)
- 【c/c++】单链表、头指针、头结点、首元节点
- Android C++层的内存收回机制
- C++函数的重载、内联和默认参数
- C++矩阵运算库推荐
- C++拷贝构造函数详解
- electron调用C++动态链接库