Skip to content

Instantly share code, notes, and snippets.

@calebreister
Last active December 31, 2015 17:09
Show Gist options
  • Save calebreister/8018174 to your computer and use it in GitHub Desktop.
Save calebreister/8018174 to your computer and use it in GitHub Desktop.
If an invalid operation is attempted on a stream, the stream variable will subsequently evaluate to false. This can be used to allow the programmer to detect and handle errors as follows...
#include <fstream>
#include <string>
using namespace std;
int main() {
string fileName = "myfile.txt";
ifstream inputData;
//open the file, if error, bail out
inputData.open(fileName);
if (! inputData) {
cout << "File " << fileName << " could not be opened.\n";
cout << "program terminated.\n";
return -1;
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment