The Member Function clear

Recall that when we try to read data from the keyboard, and if the next item in the keyboard buffer stream has a different data type compared with the data type of the variable being read, then cin enters a failed state. No further reading from cin can be successful until the failed state is cleared using cin's member function clear.

Exactly the same is true when data are being read from an input file stream.

A file stream also enters a failed state if its member function open fails to connect it to an external file.
Any further attempt to connect it with the same file or any other files will also fail unless the failed state is cleared using the member function clear.

For example, we want to connect an input file stream object ins with an external file whose name is specified by the user. When the connection fails, suppose we want to let the user enter another file name, until the connection can be made. A possible way to do that is shown below:

  ifstream ins;
  string inFileName;
  cout << "Enter the name of the input file: ";
  cin >> inFileName;
  ins.open(inFileName.c_str( ));
  while (ins.fail( ))
  {
      cout << "Cannot open file: " << inFileName << endl;
      cout << "Enter another name for the input file: "
      cin >> inFileName;
      ins.clear( );    // before we can connect ins to the file, we must first clear the failed state.
      ins.open(inFileName.c_str( ));
  }