istream提取运算符:如何检测解析失败? [英] istream extraction operator: how to detect parse failure?

查看:147
本文介绍了istream提取运算符:如何检测解析失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检测istream提取是否失败?

How can I detect whether the istream extraction failed like this?

string s("x");
stringstream ss(s);
int i;
ss >> std::ios::hex >> i;

编辑 - 虽然问题标题涵盖了这一点,我忘了在身体提到:以检测故障是由于格式不良(即解析)还是由于任何其他IO相关的问题,以提供适当的反馈(一个malformed_exception(x)或其他)。

EDIT -- Though the question title covers this, I forgot to mention in the body: I really want to detect whether the failure is due to bad formatting, i.e. parsing, or due to any other IO-related issue, in order to provide proper feedback (an malformed_exception("x") or whatever).

推荐答案

首先:感谢有用的答案。但是,经过一番调查(cfr。 cppreference )和验证后,似乎检查解析失败的唯一方法是检查 ios :: failbit 标志,如

First off: thanks for the useful answers. However, after some investigation (cfr. cppreference) and verification, it seems that the one way to check for parse-failure only is by checking for the ios::failbit flag, as in

const bool parsing_failed = (ss >> ios::hex >> i).rdstate() & ios::failbit ;

虽然建议的 istream :: operator! istream :: operator bool mingle failbit (cfr 这里 there on cplusplusreference)。

While both the suggested istream::operator! and istream::operator bool mingle failbit and badbit (cfr here and there on cplusplusreference).

这篇关于istream提取运算符:如何检测解析失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆