0

入力ファイル全体を文字列に読み込もうとしています。今私は持っています:

bool DynString::readLine(std::istream& in)
{
    if(in.eof())
    {
        *this = DynString();    // Default string value.
        return(false);
    }

    char s[1001];
    in.getline(s, 1001);

    // Delete old string-value and create new pBuff string with copy of s
    delete [] pBuff;

    pBuff = new char[strlen(s) + 1];
    DynString pBuff(s);

    return(true);
}

bool DynString::readFile(const char filename[])
{
    std::ifstream in(filename);
    if(! in.is_open() )
    {
        *this = DynString();    // Default string value.
        return(false);
    }

    // Delete old string-value and
    // Read the file-contents into a new pBuff string

    delete [] pBuff;

    DynString tempString;
    return(true);
}

ここで、pBuffはDynStringと呼ばれる動的文字列オブジェクトです。

私がしなければならないと思うのは、一時的なDynStringオブジェクトを作成し、それを一時オブジェクトとして機能させてから、readLineメソッドを使用して一時文字列をテキストファイルの行に割り当てることです。それが完了したら、古い文字列配列「pBuff」を削除してから、tempを新しいpBuff配列にコピーします。

これには、既存のpBuffに一時配列の要素を追加するだけの連結関数を使用する必要がありますか?

これがちょっと紛らわしい場合は申し訳ありませんが、ヘッダーファイルに他のメソッドがありますが、含めるには多すぎます。

4

1 に答える 1

0

次のような単純なものを使用しないのはなぜですか、またはDynStringクラスを使用する必要がありますか?

static std::string readFile(const std::string& sFile)
{
  // open file with appropriate flags
  std::ifstream in1(sFile.c_str(), std::ios_base::in | std::ios_base::binary);
  if (in1.is_open())
  {
    // get length of file:
    in1.seekg (0, std::ios::end);
    std::streamoff length = in1.tellg();
    in1.seekg (0, std::ios::beg);
    // Just in case
    assert(length < UINT32_MAX);
    unsigned uiSize = static_cast<unsigned>(length);
    char* szBuffer = new char[uiSize];
    // read data as a block:
    in1.read (szBuffer, length);
    in1.close();

    std::string sFileContent(szBuffer, uiSize);
    delete[] szBuffer;
    return sFileContent;
  }
  else
  {
     // handle error
  }
}
于 2011-02-23T04:45:40.660 に答える