简体   繁体   English

检查字符串是否为数字的最快方法是什么?

[英]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." 检查像“2.4393”或“2”这样的字符串是否有效的最快方法是什么 - 它们都可以用双 - 表示,而字符串“2.343”。 or "ab.34" are not? 或“ab.34”不是? 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并使用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 . 请参阅http://ideone.com/gpPvu8上的演示。

You can use std::stod() . 你可以使用std :: stod() If the string can not be converted, an exception is thrown. 如果无法转换字符串,则抛出异常。

as mentioned by stefan, you can use std::istringstream 正如stefan所提到的,你可以使用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 : 在我的代码中,coords是:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 检查字符串数组中是否存在字符串的最快方法是什么? - What is the fastest way to check if a string is present in a string array? 在排序范围内查找元素数量的最快方法是什么? - What's the fastest way to find the number of elements in a sorted range? 在 c++ 中找到数字因数的最快方法是什么? - What's the fastest way to find the factors of a number in c++? 检查数字是否在数字列表中的最快方法 - Fastest way to check if a number is in a list of numbers 在范围内找到质数的最快方法是什么? - What is fastest way to find a prime number in range? 检查到目前为止我在C ++中使用过哪些值的最快方法是什么? - What's the fastest way to check which values I've used so far in C++? 在C ++中,用另一个字符串替换字符串中所有出现的子字符串的最快方法是什么? - In C++, what's the fastest way to replace all occurrences of a substring within a string with another string? 重新初始化向量的最快方法是什么? - What's the fastest way to reinitialize a vector? 用C ++将不同类型的变量列表连接到逗号分隔的字符串的最快方法是什么? - What's the fastest way in C++ to concat a list of variables in different types to a comma separated string? 将double值转换为最简洁的字符串表示形式的最快或最有效的方法是什么? - What's the fastest or most efficient way to convert a double value to its most concise string representation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM