我正在使用ifstream
对象从文本文件中读取double
。
ifstreamObject >> floatVariable;
在读取无法转换为double
的情况下,我想知道如何获得不可转换的数据并将其转换为string
?有没有可能在不首先将其存储为string
然后尝试转换的情况下以这种方式进行?
我想这样做,这样对象就会抛出一个异常。catch
-块用于处理无法转换为double
的值,并将它们存储在一个单独的txt文件中以供以后分析。
使用tellg查找当前位置,如果转换失败,请使用seekg返回并将其转换为字符串。
我想重要的是要记住清除读取失败时出现的错误:
int main()
{
std::ifstream ifs("test.txt");
float f;
if(ifs >> f)
{
// deal with float f
std::cout << "f: " << f << 'n';
}
else // failed to read a float
{
ifs.clear(); // clear file error
std::string s;
if(ifs >> s)
{
// now deal with string s
std::cout << "s: " << s << 'n';
}
}
}
我建议不要使用try{} catch{}
异常,因为不可转换的输入是预期的结果之一。这并不是真正的例外。