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

V

Victor Bazarov

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

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

V
 
G

Gavin Deane

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

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
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,053
Latest member
BrodieSola

Latest Threads

Top