2

我正在学习 C++,并且正在做一个处理表示有理数(例如 ½)的类的项目。我重载了 istream>>运算符,以便它正确地从流中读取有理数。

我在将整数输入流中以获得有理数时遇到问题。例如,如果有人键入 2,我希望它从流中读取为 2/1。有人告诉我使用该peek()功能会起作用,但我不知道怎么做。这是代码:

std::istream& operator>>(std::istream& is, Rational& r)
{
  int p, q;
  char c;
  is >> p >> c >> q;

  if (!is)
    return is;

  // Require that the divider to be a '/'.
  if (c != '/') {
    is.setstate(std::ios::failbit);
    return is;
  }

  // Make sure that we didn't read p/0.
  if (q == 0) {
    is.setstate(std::ios::failbit);
    return is;
  }

  r = Rational(p, q);
  return is;
}

除非输入整数,否则它工作得很好;我希望它被读作(int)/1.

有什么建议么?

4

1 回答 1

4

如果您崩溃可能会有所帮助is >> p >> c >> q;,因此您可以在每次提取后检查流的状态(并执行peeking):

int p, q = 1; // default is 1

if(!(is >> p))
    ; // p is not good, handle it

if(is.peek() == '/')
{
    // there's an /
    is.ignore(1); // or is.get() to skip over it

    if(!(is >> q))
        ; // q is not good, handle it
}

// the following shall not be executed if extraction of q or p fails
r = Rational(p, q);

c可能不需要该变量。此外,如果有类似的东西1?,这将读取1,保持?在流中,你会得到1/1。它不是那么贪婪(你可以改变它)。

于 2016-02-17T01:29:36.783 回答