This code is a simple example of how to safely open a text file in C++. Notice the very important check that the file was opened correctly. This covers a range of errors,  most commonly file not found.


// Read integers from file and print sum.

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

using namespace std;

int main() {
 int sum = 0;
 string word;
 ifstream inFile;

 inFile.open("test.txt");
 if (!inFile) {
 cout << "Unable to open file";
 exit(1); // terminate with error
 }

 while (inFile >> word) {
 cout << word << " ";
 }

 inFile.close();

 return 0;
}

Leave a Reply

Your email address will not be published.