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”,然后将临时复制到新的 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 回答