Let's say I have a file that has
100 text
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");
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";
Get used to that format, by the way. as it comes in very handy (even more-so for continuing positive progression through loops).
If one' using GCC with -std=c++11
or -std=c++14
she may encounter:
error: cannot convert ‘std::istream {aka std::basic_istream<char>}’ to ‘bool’
Why?
The C++11 standard made bool
operator call explicit (ref). Thus it's necessary to use:
std::ifstream ifs(filename);
int a, b;
if (!std::static_cast<bool>(ifs >> a >> b))
cerr << "failed";
Personally I prefer below use of fail
function:
std::ifstream ifs(filename);
int a, b;
ifs >> a >> b
if (ifs.fail())
cerr << "failed";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With