[英]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.