Re: ifstream error
Jack wrote:
#include <iostream>
using namespace std;
Bad idea, see FAQ at parashift.com.
void getres(int &height, int &width);
Irrelevant, please make minimal examples.
ifstream inputfile; <<<<<<<<<<<< Error...
#include <fstream>
inputfile.open (inputfilename.c_str(), ios_base::in);
The 'ios_base::in' is implicitly given when you have an 'istream', same as
the 'ios_base::out' is given for an 'ostream'.
You are also missing #include <string>, BTW.
btw, when should I determine to use try/throw in C++?
Now, this is a question that requires some longer answer. In general, the
best resource for C++ questions is comp.lang.c++.moderated, BTW.
Now, the general advise is to use exceptions for exceptional cases and error
handling. Taking your example of reading a few values from a file and doing
something with it, here just for comparison the two versions using
returnvalues and exceptions.
ifstream in(filename.c_str());//1
if(!in) {
cerr << "failed to open '" << filename << "'\n";
return EXIT_FAILURE;
}
datatype data;//2
if( !read_datatype( data, in)) {//3
if(in.eof())
cerr << "unexpected end of file\n";
else
cerr << "format error in file\n";
return EXIT_FAILURE;
}
if( !data.transmogrify()) {//4
cerr << "failed to transmogrify data\n";
return EXIT_FAILURE;
}
You see that you have around four lines of 'real' code, mixed with five
mostly empty lines and 9 lines of error-checking code. Using exceptions,
this can be made much clearer:
try {
ifstream in(filename.c_str());//1
if(!in)
throw std::runtime_error("failed to open file '" + filename + "'");
datatype data;//2
read_datatype(data, in);//3
data.transmogrify();//4
} catch( std::exception const& e) {
cerr << "error: " << e.what() << '\n';
return EXIT_FAILURE;
}
Here, you have the same four lines, with two lines of error handling code in
between and four more wrapping it. The more operations you wrap in one
try{} block, the more error-handling code you concentrate in one place.
Note that if ifstream's constructor would throw exceptions to signal
failure it would have been even shorter. However, failure to open a file is
not really such an exceptional condition which is why the designers chose
to not use exceptions to signal it - opinions vary on that decision.
Uli