Bob John
Bob John

Reputation: 3878

What's the fastest way to check if a string is a number?

What's the fastest way to check that a string like "2.4393" or "2" is valid- they can both be represented by a double- whilst the strings "2.343." or "ab.34" are not? In particular, I want to be able to read any string and, if it can be a double, assign a double variable to it, and if it can't be a double (in the case that it's a word or just invalid input), an error message is displayed.

Upvotes: 2

Views: 771

Answers (4)

Chris Card
Chris Card

Reputation: 3266

Use boost::lexical_cast, which throws an exception if conversion fails.

Upvotes: 0

BЈовић
BЈовић

Reputation: 64223

You can use std::stod(). If the string can not be converted, an exception is thrown.

Upvotes: 2

hmjd
hmjd

Reputation: 121961

Use std::istringstream and confirm all data was consumed using eof():

std::istringstream in("123.34ab");
double val;
if (in >> val && in.eof())
{
    // Valid, with no trailing data.
}
else
{
    // Invalid.
}

See demo at http://ideone.com/gpPvu8.

Upvotes: 5

rxdazn
rxdazn

Reputation: 1390

as mentioned by stefan, you can use std::istringstream

coords          getWinSize(const std::string& s1, const std::string& s2)
{
  coords winSize;
  std::istringstream iss1(s1);
  std::istringstream iss2(s2);

  if ((iss1 >> winSize.x).fail())
    throw blabla_exception(__FUNCTION__, __LINE__, "Invalid width value");
  /*
   .....
  */
}

in my code, coords is :

typedef struct coords {
    int     x;
    int     y;
} coords;

Upvotes: 0

Related Questions