I/Os Bad Function In C++

In this article, we will discuss the std::ios::bad function in C++ with its syntax and examples.

The std::ios class is the root class for every single standard input/output stream in C++. It provides numerous flags that indicate the current state of the stream, one of which is called std::ios::badbit . The badbit flag signifies a critical streaming error, denoting that an unchangeable error happened during an I/O operation.

The bad member method of the std::ios class may be used to determine whether the badbit for a given stream is set. The following is how it works:

  • std::ios::badbit: A flag in the std::ios class indicates an important I/O fault. When it sets, it signals that the stream has experienced an unrecoverable error, preventing further I/O operations on the stream.
  • bad : It is a std::ios class member method that outputs a boolean value. It determines whether this stream's badbit flag is set. If the badbit is set, bad returns true, denoting a critical failure.
  • Syntax:

It has the following syntax:

Example

bool bad() const;

Parameters: No parameters are accepted by this procedure.

Return Value: If the data stream has a badbit set, this technique returns true; otherwise, it returns false.

Complexity Analysis:

Time Complexity: O(1)

Space Complexity: O(1)

Example 1: Badfun1.cpp

Example

// A C++ program to explain the working of bad() method

#include <bits/stdc++.h>
using namespace std;

int main()
{

	// stream of data
	stringstream st;

	//The bad function is used
	bool isBadstream = st.bad();

  // display the result
	cout << "Is the stream bad: "
		<< isBadstream << endl;

	return 0;
}

Output:

Output

Is the stream bad: 0

Example 2: BadFun2.cpp

Example

// A C++ program to explain the working of bad() method
#include <bits/stdc++.h>
using namespace std;

int main()
{

	// message stream
	stringstream st;
	st.clear(st.badbit);

	//The bad function is used
	bool isBadStream = st.bad();

	// display of the result
	cout << "is the stream bad: "
		<< isBadStream << endl;

	return 0;
}

Output:

Output

is the stream bad: 1

Input Required

This code uses input(). Please provide values below: