fn() lexicalCast
Interpret the character sequence in source as the numeric value and write to target.

Defined in <seqan/stream.h>
Signature bool lexicalCast(target, source); TTarget lexicalCast<TTarge>(source) // throws BadLexicalCast

Parameters

target A numeric value to write to.
source The source sequence of char to convert.

Template Parameters

TTarget The type to use for lexical cast of source.

Return Values

bool true if successful and false if there was a problem with the cast.

Detailed Description

Examples

The following example shows some lexical cast from various sequence types to numbers.

#include <iostream>
#include <string>

#include <seqan/sequence.h>
#include <seqan/stream.h>

using namespace seqan2;

int main()
{
    // interpret string literal as int
    int x = 0;
    // successful cast
    std::cout << "success=" << lexicalCast(x, "123");
    std::cout << ", x=" << x << "\n";
    // unsuccessful cast
    std::cout << "success=" << lexicalCast(x, "42a");
    std::cout << ", x=" << x << "\n";

    // interpret std::string as int
    std::cout << "success=" << lexicalCast(x, std::string("234"));
    std::cout << ", x=" << x << "\n";
    // interpret CharString as int
    std::cout << "success=" << lexicalCast(x, CharString("345"));
    std::cout << ", x=" << x << "\n";
    // interpret infix as int
    CharString str = "123";
    std::cout << "success=" << lexicalCast(x, infix(str, 1, 2));
    std::cout << ", x=" << x << "\n";

    // interpret literal as float and double
    float f = -1;
    double d = -1;
    std::cout << "success=" << lexicalCast(f, "3.1");
    std::cout << ", f=" << f << "\n";
    std::cout << "success=" << lexicalCast(d, "4.2");
    std::cout << ", d=" << d << "\n";

    // demonstrate throwing of exceptions with lexicalCast()
    try
    {
        x = lexicalCast<int>("a");
    }
    catch (BadLexicalCast const & badCast)
    {
        std::cout << "error: " << badCast.what() << "\n";
    }

    // demonstrate throwing of exceptions with lexicalCastWithException
    try
    {
        lexicalCastWithException(x, "b");
    }
    catch (BadLexicalCast const & badCast)
    {
        std::cout << "error: " << badCast.what() << "\n";
    }

    return 0;
}
success=1, x=123
success=0, x=123
success=1, x=234
success=1, x=345
success=1, x=2
success=1, f=3.1
success=1, d=4.2
error: Unable to convert 'a' into int.
error: Unable to convert 'b' into int.

Thrown Exceptions

BadLexicalCast The second variant throws BadLexicalCast in the case that casting failed.

Data Races

If not stated otherwise, concurrent invocation is not guaranteed to be thread-safe.