![](/img/trans.png)
[英]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.