what is the better way to determine if a string is number or not?

Discussion in 'C++' started by kathy, Feb 2, 2006.

  1. kathy

    kathy Guest

    what is the better way to determine if a string is number or not?
     
    kathy, Feb 2, 2006
    #1
    1. Advertisements

  2. Convert it using 'strtol' or 'strtod' and see if you convert the entire
    string. Make use of the "pointer to the error" argument.

    V
     
    Victor Bazarov, Feb 2, 2006
    #2
    1. Advertisements

  3. kathy

    Gavin Deane Guest

    You need to be clear on what formats for a number you are going to
    accept.

    For a decimal integer like 12345 it's quite easy. Just use
    std::string::find_first_not_of, or std::find_if with a predicate based
    on isdigit() to see if there are any characters that are not decimal
    digits. But what if you want to accept a decimal point 12345.678

    or negative numbers
    -12345.678

    or hexadecimal
    123abc

    scientific notation
    1.234e5

    thousands separator
    1,234,567 (could be a different character than , for the separator)

    You can write code to handle any or all of those, as long as you define
    at the outset what is acceptable. There are lots of variations of find
    functions in std::string. std::isdigit() could be helpful too.

    However, if you are happy to accept any format that iostreams accept,
    the simplest way will probably be to attempt to convert the string to a
    number and report success or failure.

    http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2

    Gavin Deane
     
    Gavin Deane, Feb 2, 2006
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.