检查像"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.
}
Run Code Online (Sandbox Code Playgroud)
请参阅http://ideone.com/gpPvu8上的演示.