| Home | Libraries | People | FAQ | More

## Examples

The following example treats command line arguments as a sequence of numeric data:

    int main(int argc, char * argv[])
    {
        using boost::lexical_cast;
        using boost::bad_lexical_cast;

        std::vector<short> args;

        while(*++argv)
        {
            try
            {
                args.push_back(lexical_cast<short>(*argv));
            }
            catch(bad_lexical_cast &)
            {
                args.push_back(0);
            }
        }
        ...
    }

The following example uses numeric data in a string expression:

    void log_message(const std::string &);

    void log_errno(int yoko)
    {
        log_message("Error " + boost::lexical_cast<std::string>(yoko) + ": " + strerror(yoko));
    }

Following example converts some number and puts it to file:

    int i;
    FILE* file;
    ...
    typedef boost::array<char, 50> buf_t; // You can use std::array if your compiler supports it
    buf_t buffer = boost::lexical_cast<buf_t>(i); // No dynamic memory allocation
    puts(buffer.begin(), file);

Following example takes part of the string and converts it to `int`:

    int convert_strings_part(const std::string& s, std::size_t pos, std::size_t n)
    {
        return boost::lexical_cast<int>(s.data() + pos, n);
    }