Is it possible to mkae std::ifstream.good() return false manually?

I am making an interpreter that heavily uses the >> operator of the std::ifstream object. Is it possible to do something along the lines of the code specified bellow:

#include <fstream>

int main() {
    std::ifstream ifstream = std::ifstream();"textfile.txt");
    char c = '\0';
    ifstream >> c
    if (c != '{') {
        // do something to ifstream object that makes ifstream.good() return false
        // Even when it read a character successfully
        // Reason: c != '{'

The reason I want to do this is because I am overriding the >> operator for a lot of objects and want to be notified when the interpreter encountered something that was not supposed to encounter, like a syntax error in the file format.

For reference, this is how overloading the operator looks like:

std::ifstream& operator >> (std::ifstream& ifstream, SomeObject& someObject) {
    // Interpret data
    // Make ifsteeam.good() return false if syntax error found

As you can see, I cannot return a bool value. If I cannot make ifstream.good() return false manually, is there an alternative and viable solution? I need this to make other pieces of my code to know that no more reading should be done when using that ifstream object.


  • Yes, using the member function setstate:

    std::ifstream& operator >> (std::ifstream& ifstream, SomeObject& someObject) {
        // process stuff
        if (something_failed) {
        return ifstream;