The C++ std::ios::good() function is a member of the std::ios class, which is the part of input/output stream library. This function checks the state of an I/O stream to determine if it is in a good state(no errors occurred) or not. It returns true if it is in good state otherwise it returns false.
SyntaxFollowing is the syntax for std::ios::good() function.
bool good() const;Parameters
It does not accept any parameter.
Return valueIt returns true if the condition holds, otherwise false.
ExceptionsIf an exception is thrown, there are no changes in the stream.
Data RacesAccesses the stream object.
Concurrent access to the same stream object may cause data races.
ExampleIn the following example, we are going to check standard input stream.
#include <iostream> int main() { std::cout << "Enter A Number : "; int x; std::cin >> x; if (std::cin.good()) { std::cout << "Entered Number Is : " << x << "\n"; } else { std::cout << "Input Not Found.\n"; } return 0; }Output
Output of the above code is as follows −
Enter A Number : 123 Entered Number Is : 123Example
Consider the following example, where we are going to ask user to enter two integers. if both the inputs are successful, good() return true.
#include <iostream> int main() { std::cout << "Enter two integers: "; int x, y; std::cin >> x >> y; if (std::cin.good()) { std::cout << "Sum: " << x + y << std::endl; } else { std::cout << "Error." << std::endl; } return 0; }Output
Following is the output of the above code −
Enter two integers: 1 2 Sum: 3Example
Let's look at the following example, where we are going to read multiple types of input in a single statement.
#include <iostream> int main() { std::cout << "Input : "; int x; std::string y; std::cin >> x >> y; if (std::cin.good()) { std::cout << "Number: " << x << ", String: " << y << std::endl; } else { std::cout << "Input error." << std::endl; } return 0; }Output
If we run the above code it will generate the following output −
Input : 1TP Number: 1, String: TP
ios.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4