我使用ifstream对象从文本文件中读取double。
ifstreamObject >> floatVariable;在读取无法转换为double的情况下,我想知道如何才能获得不可转换的数据并将其转换为string?是否有可能这样做,而不首先将其存储为string,然后尝试转换它?
我想这样做,这样对象就会抛出异常。catch-block用于处理不能转换到double的值,并将它们存储在单独的txt文件中供以后分析。
发布于 2014-09-29 18:16:53
使用tellg查找当前位置,如果转换失败,请使用seekg返回并将其转换为字符串。
发布于 2014-09-29 18:30:37
我认为重要的是要记住清除当读取失败时所得到的错误:
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{}异常,因为不可转换的输入是预期的结果之一。这并不是真正的例外。
https://stackoverflow.com/questions/26106182
复制相似问题