本文介绍了检查是否所有值均已成功从std :: istream读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我的文件具有
100 text如果我尝试使用ifstream读取2个数字,则会失败,因为text不是数字.通过使用fscanf,我将通过检查其返回码来了解它是否失败:
If I try reading 2 numbers using ifstream, it would fail because text is not a number. Using fscanf I'll know it failed by checking its return code:
if (2 != fscanf(f, "%d %d", &a, &b)) printf("failed");但是当使用iostream代替stdio时,我怎么知道它失败了?
But when using iostream instead of stdio, how do I know it failed?
推荐答案实际上(如果不是更多的话)很简单:
Its actually as (if not more) simple:
ifstream ifs(filename); int a, b; if (!(ifs >> a >> b)) cerr << "failed";顺便说一下,习惯了这种格式. (非常方便)(对于通过循环继续 positive 持续进展更是如此)
Get used to that format, by the way. as it comes in very handy (even more-so for continuing positive progression through loops).
更多推荐
检查是否所有值均已成功从std :: istream读取
发布评论