检查是否所有值均已成功从std :: istream读取

编程入门 行业动态 更新时间:2024-10-28 11:18:35
本文介绍了检查是否所有值均已成功从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读取

本文发布于:2023-10-11 17:35:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1482370.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:均已   std   istream

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!