覆盖运算符>>对于一个字符串类

时间:2010-11-09 20:04:42

标签: c++ operator-overloading istream

我只是一个简单的问题。我需要覆盖运算符>>对于自定义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()以外的其他东西吗?

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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是否包含空格,而不是您是否从流中读取空格。