Get out of an overloaded mining operator? (C ++)

I am trying to use the overloaded "→" to scan input from a file.

The problem is that I have no idea how to deal with the end of the file. In this case, my file consists of a number and then a few characters

Example:

9rl

8d

6 onwards

istream &operator>>(istream &is, Move &move) { char c; int i = 0; c = is.get(); if (!isalnum(c)) return; move.setNum(c); // I convert the char to an int, but I'l edit it out while ( (c = is.get()) != '\n') { move.setDirection(i, c); //sets character c into in array at index i i++; } // while chars are not newline return is; } // operator >> 

The test for a character that was alphanumeric worked when I had it as a normal function, but does not work here, as it expects the returned stream to be returned. I also tried to return NULL. Suggestions?

EDIT: this is called in a while loop. So I'm trying to figure out how this trigger has some flag so that I can exit the loop. In my previous function, I returned a boolean returning true if it was successful or false if the character was not alphanumeric

+4
source share
2 answers

Refund is . Subscribers should check the flow for errors.

Be sure to set the corresponding error bits:

 std::istream &operator>>(std::istream &is, Move &move) { char c; int i = 0; c = is.get(); if (is.eof()) return is; else if (c < '0' || c > '9') { is.setstate(std::ios::badbit); return is; } else move.setNum(c-'0'); while ( (c = is.get()) != '\n' && is) move.setDirection(i++, c); if (c != '\n') is.setstate(std::ios::badbit); return is; } 

Use it as in the following:

 int main(int argc, char **argv) { std::stringstream s; s << "9rl\n" << "8d\n" << "6ff\n"; s.seekg(0); Move m; while (s >> m) std::cout << m; if (s.bad()) std::cerr << argv[0] << ": extraction failed\n"; return 0; } 

Note that the code uses an instance of m only after successful retrieval.

+2
source

You can set the stream flags to a state such as ios :: bad or ios :: fail using ios :: setstate . This will allow the caller to test the stream, or if exceptions are enabled for the stream, an exception will be thrown.

You also cannot check the status of your stream. The C ++ FAQ lite has a great section explaining this. To clarify this, I added the code snippet below.

 c = is.get(); // the stream has not been tested to see if it read into c correctly if (!isalnum(c)) return; 
+2
source

Source: https://habr.com/ru/post/1300829/


All Articles