问题01:如何将字符串形式的数值转换为诸如int或float之类的数值类型
定义在<cstdlib>中的strtol、strtod和strtoul函数可以将以null结尾的字符串转换为long int、double或unsigned long类型的数值。你可以使用他们把任意进制的字符串转换为数值(相比之下,atoi函数只能转换十进制数值,并且没有错误返回)。
- #include <iostream>
- #include <string>
- #include <cstdlib>
- using namespace std;
- int main()
- {
- char *offset; // 接收解析结束地址
- string s1 = "520";
- cout << strtol(s1.c_str(), &offset, 0) << endl;
- string s2 = "0xA";
- cout << strtol(s2.c_str(), &offset, 16) << endl;
- return 0;
- }
问题02:如何将int或float类型的数值转换为某种格式的字符串
使用stringstream类来存储字符串数据。stringstream是一种把数据转换成字符串的简便方法,因为它允许使用由标准输入输出流类提供的格式化工具。
- #include <iostream>
- #include <string>
- #include <sstream>
- #include <iomanip>
- using namespace std;
- int main()
- {
- stringstream ss;
- ss << 9;
- cout << ss.str() << endl;
- ss.str("");
- ss << showbase << hex << 16;
- cout << ss.str() << endl;
- ss.str("");
- ss << setprecision(3) << 3.1415;
- cout << ss.str() << endl;
- return 0;
- }
问题03:如何把用科学计数法表示的数值字符串存储到double变量中
要解析用科学计数法表示的数值,最直接的方法是使用C++函数库在<sstream>中内置的streamstring类。
- #include <iostream>
- #include <sstream>
- #include <string>
- using namespace std;
- int main()
- {
- stringstream ss("1.234e5");
- double d = 0;
- ss >> d;
- if(ss.fail()) {
- string e = "Unable to format";
- throw(e);
- }
- cout << d << endl;
- return 0;
- }
问题04:如何获得某种数值类型的最值
使用<limits>中的numeric_limits类模板可以知道某个数值类型所能表示的最大值和最小值,min和max是numeric_limits的静态成员函数。
- #include <iostream>
- #include <limits>
- using namespace std;
- int main()
- {
- cout << numeric_limits<int>::min() << endl;
- cout << numeric_limits<int>::max() << endl;
- return 0;
- }