在 2D 指针和重新生成中从文件输入字符时出现异常错误

Exception Error while char input from file in 2D Pointers and Regrowing

我正在尝试将名称从文件输入到双指针。因为,文件结构是这样的,我不知道我会遇到多少名字。我在 运行 时间重新生成 2D 和 1D 指针。但问题是,因为我在我的 while 循环中使用 fin.eof() 。输入所有名称后,循环不会检测文件末尾并将另一个数组添加到 2D 指针,因为它还没有分配任何内存。然后它尝试将 '\0' 添加到未分配的内存中,然后抛出异常错误。

#include <iostream>
#include <fstream>

using namespace std;

void OneDRegrow(char * & ptr, int & size)
{
    char * temp = new char[size];
    for (int i = 0; i < size; i++)
    {
        temp[i] = ptr[i];
    }
    if(!ptr)
        delete[] ptr;
    ptr = temp;
    size++;
}

void TwoDRegrow(char ** & ptr, int & size)
{
    char ** temp = new char*[size + 1];
    for (int i = 0; i < size; i++)
    {
        temp[i] = ptr[i];
    }
    delete[] ptr;
    ptr = temp;
    temp = nullptr;
    size++;
}

bool Read(ifstream & fin, char ** & ptr, int & rows)
{
    if (!fin.is_open())
        return false;
    rows = 0;
    int cols = 0;
    char ch = '[=10=]';
    while (!fin.eof()) {
        TwoDRegrow(ptr, rows);
        cols = 0;
        fin >> ch;
        while (ch != ';') {
            OneDRegrow(ptr[rows-1], cols);
            ptr[rows - 1][cols-1] = ch;
            fin >> ch;
        }
        ptr[rows - 1][cols] = '[=10=]';
    }
}

void Print2D(char ** ptr, int size)
{
    for (int i = 0; i < size; i++)
    {
        cout << ptr[i] << endl;
    }
}

int main()
{
    int size;
    char ** ptr = NULL;
    ifstream fin("input.txt", ios::in);
    Read(fin, ptr, size);
    Print2D(ptr, size);
    system("pause");
    return 0;
}

我的文件输入如下:

Roger;
James;
Mathew;
William;
Samantha;

做正确的事

while (fin >> ch) {
    TwoDRegrow(ptr, rows);
    cols = 0;
    while (ch != ';') {
        ...

从不(几乎)使用 eof 作为 while 循环中的条件,原因正是您所发现的。