简体   繁体   中英

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.

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 .

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

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;

使用boost::lexical_cast ,如果转换失败,则抛出异常。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM