ios::good() and ios::bad() functions in C++

ios::good() and ios::bad() functions in C++ are used to check the state of the stream whether it is good or bad to do our task. Both of these are defined in ios library. These functions have been explained below in detail.

ios::good()

The syntax for good() function can be given as shown here:

bool good() const;

As the syntax above suggests the function returns a boolean value specifying if the current stream is good to go or not. For good, it returns 1 otherwise it returns 0. The good() function takes no parameters.

Here, an example program is given to explain its working. Go through the code to understand the concept.

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
  stringstream s;
  bool ret;
  ret = s.good();
  
  if(ret == 1)
    cout << "The current stream is good to go." << endl;
  else
    cout << "The current stream is not good enough." << endl;
    
  return 0;
}

Output:

The current stream is good to go.

ios::bad()

The syntax of bad() function is:

bool bad() const;

This function returns 1 if the current stream is not good enough to work and 0 otherwise. This function also takes no parameter same as the good() function.

Have a look at the following to grasp the concept and working of this function.

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
  stringstream s;
  bool ret;
  
  ret = s.bad();
  
  if(ret == 0)
    cout << "The current stream is good to go." << endl;
  else
    cout << "The current stream is not good enough." << endl;
    
  //changing the state of the current stream
  s.clear(s.badbit);
  cout << "\nAfter changing the state of the stream to bad------\n";
  ret = s.bad();
  
  if(ret == 0)
    cout << "The current stream is good to go." << endl;
  else
    cout << "The current stream is not good enough." << endl;
    
  return 0;
}

Output:

The current stream is good to go.

After changing the state of the stream to bad------
The current stream is not good enough.

Thank you.

Also read: Virtual Base Class in C++ with an Example

Leave a Reply