2

"2.4393" や "2" のような文字列が有効であることを確認する最も速い方法は何ですか。または「ab.34」ではありませんか?特に、任意の文字列を読み取ることができるようにしたいのですが、それが double になる可能性がある場合は double 変数を割り当て、それが double にならない場合 (それが単語または単に無効な入力の場合) 、エラーメッセージが表示されます。

4

4 に答える 4

5

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.

于 2012-12-06T11:46:23.990 に答える
2

std::stod()を使用できます。文字列を変換できない場合は、例外がスローされます。

于 2012-12-06T11:55:04.353 に答える
0

ステファンが述べたように、使用できます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");
  /*
   .....
  */
}

私のコードでは、座標は次のとおりです。

typedef struct coords {
    int     x;
    int     y;
} coords;
于 2012-12-06T11:43:48.890 に答える
0

Use boost::lexical_cast, which throws an exception if conversion fails.

于 2012-12-06T11:48:27.140 に答える