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;
}

ただし、仕様(これは宿題です)によると、空白を手動でチェックし、文字列がdata []に対して大きすぎないことを確認するために、一度に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();
    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;
}

2番目のバージョンをベースとして使用する:

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 に答える