Boost lexical_cast format

Source: Internet
Author: User

Boost includes five strings and libraries in the text processing field:
[1] Two lexical_cast and format functions are similar to the functions of the C standard library. They focus on the representation of strings and can convert values into strings to precisely format the output.
[2] The string_algo Library provides a large number of commonly used string processing functions.
[3] tokenizer and xpressive, the former is a word divider, the latter is a flexible Regular Expression analyzer, and also a syntax analyzer.

Lexical_cast:
The lexical_cast library converts "literal". Similar to the atio function in C, it can convert strings, integers, and floating-point numbers.
# Include <boost/lexical_cast.hpp>
Using namespace boost;
Usage:

Lexcial_cast provides general, consistent, and understandable syntax in a format similar to the C ++ 98 standard transformation operator (xxx_cast.
Lexcical_cast can be easily converted between values and strings. You only need to specify the conversion target type in the template parameters. For example:
# Include <iostream>
# Include <boost/lexical_cast.hpp>
Using namespace boost;
Using namespace STD;
Int main ()
{
Int x = lexical_cast <int> ("100 ");
Long y = lexical_cast <long> ("2000 ");
Float Pai = lexical_cast <float> ("3.14159e5 ");
Double E = lexical_cast <double> ("2.71828 ");
Cout <x <"," <Y <"," <Pai <"," <e <Endl;
String STR = lexical_cast <string> (456 );
Cout <STR <Endl;
Cout <lexical_cast <string> (0.618) <Endl;
Cout <lexical_cast <string> (0x10) <Endl;
System ("pause ");
Return 0;
}
Note: The string to be converted to a number can only contain numbers and decimal places, and cannot contain letters (except E/E indicating the index) or other non-numeric characters, that is, lexcical_cast cannot convert numeric literal strings licensed by C ++ syntax such as "123l", "0x100", and lexcical_cast does not support advanced format control, numbers cannot be converted to strings in the specified format. For more advanced format control, you can use STD: stringstream or boost: format;
In addition to converting numeric values and strings, lexcical_cast can also be converted to the bool type, but it has limited functions. It cannot use True/false literal values, but can only use 1 or 0;
Cout <lexical_cast <bool> ("1") <Endl;

Exception bad_lexical_cast
When lexcical_cast cannot perform the conversion operation, it will throw an exception bad_lexical_cast, which is a derived class of STD: bad_cast. To make the program more robust, use try/Catch Block to protect the conversion code;
Example:
# Include <iostream>
# Include <boost/lexical_cast.hpp>
Using namespace boost;
Using namespace STD;
Int main ()
{
Try
{
Cout <lexical_cast <int> ("0x100") <Endl;
Cout <lexical_cast <double> ("helloworld") <Endl;
Cout <lexical_cast <long> ("100l") <Endl;
Cout <lexical_cast <bool> ("false") <Endl;
}
Catch (bad_lexical_cast & E)
{
Cout <"error:" <E. What () <Endl;
}
System ("pause ");
Return 0;
}
You can also use bad_lexical_cast to verify the validity of the numeric string. The code for implementing a template function num_valid () is as follows:
Template <typename T>
Bool num_valid (const char * Str)
{
Try
{
Lexical_cast <t> (STR );
Return true;
}
Catch (bad_lexical_cast &)
{
Return false;
}
}
Int main ()
{
Assert (num_valid <double> ("3.14 "));
Assert (! Num_valid <int> ("3.14 "));
Assert (num_valid <int> ("65535 "));
System ("pause ");
Return 0;
}

Requirements for conversion objects:
Lexical_cast is actually a template function that uses stream operations in the standard library internally. Therefore, it has the following requirements for its conversion object:
[1] The conversion start object is streamable, that is, the operator is defined. <;
[2] The end object of the conversion is stream input, that is, operator> is defined;
[3] The destination object to be converted must be default and copyable;
Both the built-in types (INT, double, etc.) and STD: String in C ++ meet the preceding three conditions;

Apply to your own class:
To apply lexcical_cast to a custom class and convert the class to an understandable string description, you only need to meet the requirements of lexcical_cast. To be precise, you need to implement the stream output Operator <;
Example:
# Include <iostream>
# Include <boost/lexical_cast.hpp>
Using namespace boost;
Using namespace STD;
Class demo_class
{
Friend STD: ostream & operator <(STD: ostream & OS, const demo_class & X)
{
OS <"demo_class's name ";
Return OS;
}
};
Int main ()
{
Cout <lexical_cast <string> (demo_class () <Endl;
System ("pause ");
Return 0;
}
This code is worth extracting a template class that can be used to simulate boost. operator library, defines a template class outable to simplify the stream output operator Example:
# Include <iostream>
# Include <boost/lexical_cast.hpp>
Using namespace boost;
Using namespace STD;
Template <typename T>
Struct outable
{
Friend STD: ostream & operator <(STD: ostream & OS, const T & X)
{
OS <typeid (T). Name ();
Return OS;
}

};
Class demo_class: outable <demo_class>
{};
Int main ()
{
Cout <lexical_cast <string> (demo_class () <Endl;
System ("pause ");
Return 0;
}
In this way, any class that inherits the outable will automatically obtain the stream output operator <or lexcical_cast support
Based on the same principle, you can also overload the Stream Input operator>.

Format:
Boost. format can format the parameter to a string, and it is completely type-safe.
# Include <boost/format. HPP>
Using namespace boost;
Simple Example:
# Include <assert. h>
# Include <iostream>
# Include <boost/format. HPP>
Using namespace boost;
Using namespace STD;
Int main ()
{
Cout <format ("% s: % d + % d = % d \ n") % "sum" % 1% 2% (1 + 2 );
Format FMT ("(% 1% + % 2%) * % 2% = % 3% \ n ");
FMT % 2% 5;
FMT % (2 + 5) * 5 );
Cout <FMT. STR ();
System ("pause ");
Return 0;
}

Input operator %:
Why are heavy-duty operators used:
For type security considerations, the format cannot use ellipsis to implement variable parameters. If you use the function call form, you need to define the number of template functions with different parameters, such:
Template <class T1, class T2,..., class TN>
String format (string S, const T1 & X1,..., const T1 & XN );
Before C ++ implements variable number of template parameters, no matter how many such overload forms are defined, it cannot meet the needs of formatting "unlimited" parameters. Therefore, parameters must be accepted using operators, and the operator of the IO stream

The binary Operator % () is declared as follows:
Format & operator % (T & X );
It accepts the format object and any value as the parameter, and then returns the reference of the format object, so it can implement the % operator on the returned format object, so:
Format ("...") % x % Y
It is interpreted by the compiler:
Operator % (format ("..."), x) % Y =>
Operator % (operator % format ("..."), x), Y)
And so on, so as to accept unlimited parameters to be formatted.

Class Abstract:
Format is not a real class, but a typedef. The true implementation is basic_format.
Format Syntax:
The format basically inherits the formatting Syntax of printf, and only has a small amount of incompatibility with the printf syntax;
 
Each printf formatting option starts with %, followed by a format rule that specifies the alignment, width, and character type of the output:
[1] % 05d; an integer with an output width of 5. Fill the insufficiency with 0
[2] %-8.3f; left alignment of the output. The total width is 8 and the decimal point number is 3 digits.
[3] % 10 s; outputs a 10-Bit String. Fill in spaces for the missing characters.
[4] % 05x; the output width is a hexadecimal integer of 5, and the number of digits is filled with 0.
In addition to the classic printf format, the format also adds a new format:
[5] % | spec |: The function is the same as that of the printf format option, but the two sides are separated by vertical bars to better distinguish formatting options from common characters;
[6] % N %; mark the nth parameter, which is equivalent to a placeholder without any other formatting options.

Advanced usage:
Format provides functions similar to printf, but it is not equivalent to the printf function. This is the benefit of object-oriented. Besides common formatting strings, the format class also has several advanced functions, you can modify the formatting options and bind the input parameters during the operation.
These advanced functions use the following functions:
[1] basic_format & bind_arg (INT argn, const T & Val)
The input parameter at the argn position of the formatted string is fixed to Val, and remains unchanged even if clear () is called unless clear_bind () or clear_binds () is called ().
[2] basic_format & clear_bind (INT argn)
Unbind the parameter at the argn position of the formatted string.
[3] basic_format & clear_binds ()
Unbind the parameters at all positions of the formatted string and call clear ().
[4] basic_format & modify_item (INT itemn, t Manipulator)
Sets the formatting option for the itemn position of the formatted string. manipulator is an object returned by boost: IO: group.
[5] boost: IO: group (T1 Al,..., VAR const & var)
It is a template function that supports a maximum of 10 parameters (10 reloads). You can set Io stream manipulation to a specified format or input parameter values. The IO stream manipulator is located in the header file <iomanip>.
 
Example:
# Include <iostream>
# Include <boost/format. HPP>
# Include <iomanip>
Using namespace boost;
Using boost: IO: group;
Using namespace STD;
Int main ()
{
// Declare the format object. There are three input parameters and five formatting options.
Format FMT ("% 1% % 2% % 3% % 2% % 1% \ n ");
Cout <FMT % 1% 2% 3;
FMT. bind_arg (2, 20); // set the second input parameter to a number of 20
Cout <FMT % 1% 3; // enter the remaining two parameters
FMT. Clear (); // clear the buffer, but the bound parameters remain unchanged.
// Use group () in the operator to specify that the first parameter of the IO stream operator is displayed as octal.
Cout <FMT % group (showbase, Oct, 111) %333;
FMT. clear_binds (); // clear all binding parameters
// Set the first formatting item, in hexadecimal format, with a width of 8 and right alignment. fill in the missing digits *.
FMT. modify_item (1, group (Hex, right, showbase, SETW (8), setfill ('*')));
Cout <FMT % 49% 20% 100;
System ("pause ");
Return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.