c++ - 重写 operator>> 用于 Strings 类

标签 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() 以外的东西吗?

最佳答案

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

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 是否包含空格,而不是您是否从流中读取了空格。

关于c++ - 重写 operator>> 用于 Strings 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4137992/

相关文章:

c++ - 我可以用c++中的istream读取二进制数据吗?

c++ - 如何识别库是 DEBUG 还是 RELEASE 构建?

c++ - isPrime 函数的改进

c++ - 前缀和后缀运算符继承

c++ - 需要帮助来完成对 k 个已排序流进行排序的功能

c++ - 在 main() 中控制 cin

c++ - 将记录作为函数结果从 Delphi DLL 传递到 C++

c++ - 具有不同长度的两个 vector 数组的线性插值

c++ - 如何在 C++ 中实现以逗号分隔的初始化,例如 Eigen 中的初始化?

c++ - 为什么 cout << 不能与重载的 * 运算符一起工作?