The LEXical_cast function in the Boost library is very powerful, but there is a precision problem with a floating point number. The following is described in Ai's "walk into Boost":
#include #include #include int main () {using std :: string; const Double d = 123.1234567; string s = boost :: lexical_case (d); Std :: cout << S << std :: end1; return 0;}
The results expected by the above procedures were obtained: "123.1234567", but in fact we only get "123.123", because the accuracy of std :: StringStream is 6. This is a bug of Boost :: Lexical_cast.
Ah provides a solution: the header file makes the following modification: // .... Template Target Lexical_cast (Source Arg) {// ..... Target Result ; // The above line is increasing content interpreter.Precision (std :: numeric_limits
I can't get the correct result in my machine in my machine. (BCB 6) Even if it is feasible, there is also the following problem: only a string of accuracy can be obtained.
I use the following methods to solve the above problems:
Use the function overload mechanism in C , add a function: Template Target Lexical_cast (Source Arg) {// ... Target Result; if (! (Interpreter << arg) || ! (Interpreter >> Result) | (Interpreter >> std :: ws) .eof ()) // ....} Template // The following line modified Target Lexical_cast (Source Arg , int length) {# ifdef BOOST_LEXICAL_CAST_USE_STRSTREAM std :: strstream interpreter; // for out-of-the-box g 2.95.2 # else std :: stringstream interpreter; # endif Target result; // Add the following line interpreter.precision ( Length); if (! ("(Interpreter << arg) ||! (interpreter >> result) ||! (interpreter >> std :: ws) .eof ()) throw bad_lexical_cast (); return result;}}
When used: std :: string s = boost :: lexical_cast (123.1234567, 10); to get the correct result, and the original function is unchanged.
summary
No matter how good things, there will always be some small problems and inexpensive things, it is a good thing to do it.