[英]What is the fastest way to check if a string is present in a string array?
[英]What's the fastest way to check if a string is a number?
检查像“2.4393”或“2”这样的字符串是否有效的最快方法是什么 - 它们都可以用双 - 表示,而字符串“2.343”。 或“ab.34”不是? 特别是,我希望能够读取任何字符串,如果它可以是双精度型,请为其分配一个双精度变量,如果它不能是双精度型(在它是单词或只是无效输入的情况下) ,显示错误消息。
使用std::istringstream
并使用eof()
确认所有数据已被使用:
std::istringstream in("123.34ab");
double val;
if (in >> val && in.eof())
{
// Valid, with no trailing data.
}
else
{
// Invalid.
}
你可以使用std :: stod() 。 如果无法转换字符串,则抛出异常。
正如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");
/*
.....
*/
}
在我的代码中,coords是:
typedef struct coords {
int x;
int y;
} coords;
使用boost::lexical_cast
,如果转换失败,则抛出异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.