0

我只是有一个简单的问题。我需要为自定义 String 类覆盖运算符 >> ,但我不知道该怎么做。

我知道这段代码有效,因为这是我解决问题的原始方法:

istream& operator>>(istream &is, String &s) {
  char data[ String::BUFF_INC ];  //BUFF_INC is predefined
  is >> data;
  delete &s;
  s = data;
  return s;
}

但是,根据规范(这是一项家庭作业),我需要一次读取字符 1 以手动检查空格并确保字符串对于 data[] 来说不会太大。因此,我将代码更改为以下内容:

istream& operator>>(istream &is, String &s) {
  char data[ String::BUFF_INC ];
  int idx = 0;
  data[ 0 ] = is.get();
  while( (data[ idx ] != *String::WHITESPACE) && !is.ios::fail() ) {
    ++idx;
    is.get();
    data[ idx ] = s[ idx ];
  }
  return is;
}

但是,当执行此新代码时,它只会卡在用户输入循环中。那么如何使用 is.get() 逐字符读取数据而不等待更多用户输入?或者我应该使用 .get() 以外的东西吗?

4

2 回答 2

1

尝试:

istream& operator>>(istream &is, String &s)
{
    std::string  buffer;
    is >> buffer;           // This reads 1 white space separated word.

    s.data = buffer.c_str();
    return is;
}

评论您的原始代码:

istream& operator>>(istream &is, String &s)
{
  char data[ String::BUFF_INC ];
  is >> data;   // Will work. But prone to buffer overflow.


  delete s;    // This line is definately wrong.
               // s is not a pointer so I don;t know what deleting it would do.

  s = data;    // Assume assignment operator is defined.
               // for your class that accepts a C-String
  return s;
}

使用第二个版本作为基础:

istream& operator>>(istream &is, String &s)
{
  std::vector<char> data;

  char first;
  // Must ignore all the white space before the word
  for(first = is.get(); String::isWhiteSpace(first) && is; first = is.get())
  {}

  // If we fond a non space first character
  if (is && !String::isWhiteSpace(first))
  {
      data.push_back(first);
  }


  // Now get values while white space is false
  char next;
  while( !String::isWhiteSpace(next = is.get()) && is)
  {
      // Note we test the condition of the stream in the loop
      // This is because is.get() may fail (with eof() or bad()
      // So we test it after each get.
      //
      // Normally you would use >> operator but that ignores spaces.
      data.push_back(next);
  }
  // Now assign it to your String object
  data.push_back('\0');
  s.data = data;
  return is;
}
于 2010-11-09T20:09:13.197 回答
1

您似乎没有对从流中获得的角色做任何事情

istream& operator>>(istream &is, String &s) {
  char data[ String::BUFF_INC ];
  int idx = 0;
  data[ 0 ] = is.get();
  while( (data[ idx ] != *String::WHITESPACE) && !is.ios::fail() ) {
    ++idx;
    is.get();              // you don't do anything with this
    data[ idx ] = s[ idx ]; // you're copying the string into the buffer
  }
  return is;
}

因此它检查字符串 s 是否包含空格,而不是您是否从流中读取空格。

于 2010-11-09T20:12:37.310 回答