| | | | | |

String Implementation: I/O Operators

  std::ostream& operator << (std::ostream& os, const String& s)
  {
    if (s.data_ != 0)
      os << s.data_;
    return os;
  }

  static const size_t initBuffSize = 25;
  // used as size increment for local buffer during extraction

  std::istream& operator >> (std::istream& is, String& s)
  {
    // Debug d("operator >> ()");
    size_t currSize = 0, buffSize = initBuffSize;

    // skip clearspace
    char x;
    is >> x;
    if (is.fail() || is.eof())
      {
        return is;
      }

    // space for temporary char storage
    char* buffer = String::NewCstr(buffSize);

    // insert x and continue reading contiguous non-clearspace
    buffer[currSize++] = x;
    x = is.peek();
    while ((x != ' ') && (x != '\n') && (x != '\t') && (!is.eof()))
      {
        if (currSize == buffSize)  // need more buffer 
          {
            buffSize *= 2;
            char* newbuffer = String::NewCstr(buffSize);
            for (size_t i = 0; i < currSize; ++i)
              {
                newbuffer[i] = buffer[i];
              }
            delete [] buffer;
            buffer = newbuffer;
          }
        buffer[currSize++] = x;
        is.get();
        x = is.peek();
      }
    buffer[currSize] = '\0';
    s.Wrap(buffer);
    delete [] buffer;
    return is;
  }

| | Top of Page | 3. C Strings, Proper Type, and String Objects - 12 of 17