問題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;
- }
- #include <iostream>
- #include <limits>
- using namespace std;
- int main()
- {
- cout << numeric_limits<int>::min() << endl;
- cout << numeric_limits<int>::max() << endl;
- return 0;
- }