庫“boost/lexical_cast.hpp”中定義的Boost.LexicalCast提供了強製轉換運算符boost::lexical_cast,可以將數字從字符串轉換為數字類型,如int或double,反之亦然。
boost::lexical_cast是std::stoi(,std::stod(和std::to_string()等函數的替代方法,它們已添加到C++ 11中的標準庫中。現在讓我們在程序中查看此函數的實現。例子:
Conversion integer -> string string- > integer integer -> char float- > string
關聯的異常:如果轉換失敗,則引發從bad_cast派生的bad_lexical_cast類型的異常。引發異常是因為浮點數52.50和字符串“GeeksforGeeks”無法轉換為int類型的數字。
// CPP program to illustrate
// Boost.Lexical_Cast in C++
#include "boost/lexical_cast.hpp"
#include <bits/stdc++.h>
using namespace std;
using boost::lexical_cast;
using boost::bad_lexical_cast;
int main() {
// integer to string conversion
int s = 23;
string s1 = lexical_cast<string>(s);
cout << s1 << endl;
// integer to char conversion
array<char, 64> msg = lexical_cast<array<char, 64>>(45);
cout << msg[0] << msg[1] << endl;
// string to integer conversion in integer value
int num = lexical_cast<int>("1234");
cout << num << endl;
// bad conversion float to int
// using try and catch we display the error
try {
int num2 = lexical_cast<int>("52.20");
}
// To catch exception
catch (bad_lexical_cast &e) {
cout << "Exception caught:" << e.what() << endl;
}
// bad conversion string to integer character
// using tru and catch we display the error
try {
int i = lexical_cast<int>("GeeksforGeeks");
}
// catching Exception
catch (bad_lexical_cast &e) {
cout << "Exception caught:" << e.what() << endl;
}
return 0;
}
輸出:-
23 45 1234 Exception caught:bad lexical cast:source type value could not be interpreted as target Exception caught:bad lexical cast:source type value could not be interpreted as target
參考:-http://www.boost.org/
注:本文由純淨天空篩選整理自ajay0007大神的英文原創作品 Boost.Lexical_Cast in C++。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。