Jump to

v03-l2-findError

There is one error is the following program, which is ...

#include <iostream>
#include <string>
#include <fstream>
using std::ofstream, std::cout, std::endl;

int main() {
  ofstream outputFile();
  outputFile.open("textFile.txt");
  if (outputFile.is_open()) {
      outputFile << "Let there be some words" << endl
                 << "Oh that's great" << endl;
      outputFile.close();
  } else cout << "Could not open the file" << endl;
  return 0;
}

???

Remember the classical pitfall with C++ variable declaration :

int i;    // Declaration of a variable
int j{};  // Declaration of a variable
int k();  // Declaration of a function named k, that takes no argument and return an int !

So when doing this :

ofstream outputFile();

we are doing the same thing as for k. The correct line is then :

ofstream outputFile;

Eventually, you can also open the file when declaring the outputFile variable, for instance like this :

ofstream outputFile("textFile.txt");

but then, you must not call the open method on the outputFile object, except if you used the close method before ....