促进LexicalCast在库“boost/lexical_cast.hpp”中定义,它提供了一个cast操作符boost::lexical_cast,可以将数字从字符串转换为int或double等数字类型,反之亦然。
null
词法_cast是诸如 std::stoi() , std::stod() 和 std::to_string() ,它们被添加到C++11中的标准库中。 现在让我们看看这个函数在程序中的实现。 例如:
Conversion integer -> string string- > integer integer -> char float- > string
相关例外情况: 如果转换失败,将抛出bad_词法_cast类型的异常,该异常派生自bad_cast。它抛出一个异常,因为float 52.50和字符串“geeksforgeks”无法转换为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
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END