>\" to scan input from a file. The problem is, I have no idea how to deal with end of file." />
开发者

Break out of an overloaded extraction operator? (C++)

I'm trying to use an overloaded ">>" to scan input from a file.

The problem is, I have no idea how to deal with end of file. In this case, my file is composed of a number, followed by several chars

Ex:

9rl

8d

6ff

istream &operator>>(istream &a开发者_运维问答mp;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 the character being alpha numeric worked when I had this as a regular function, but doesn't work here as it expects an input stream to be returned. I've tried returning NULL as well. Suggestions?

EDIT: this is being called in a while loop, So i'm trying to figure out some way to have this trigger some flag so that I can break out of the loop. In my previous function, I had this return a boolean, returning true if successful or false if the character was not alphanumeric


Return is. Callers should check the stream for errors.

Be sure to set error bits as appropriate:

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;
}

Notice that the code uses the instance m only after successful extraction.


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

You also fail to check the state of your stream. The C++ FAQ lite has a great section explaining this. To clarify this I have 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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜