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

问题描述 投票:1回答:1

我试图将文件中的名称输入到双指针。因为,文件结构是这样的,我不知道我会遇到多少名字。我在运行时重新生成指针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 = '\0';
    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] = '\0';
    }
}

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;
c++ exception character fileinputstream double-pointer
1个回答
0
投票

以正确的方式做到这一点

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

从来没有(几乎)使用eof作为while循环中的条件,这正是您找到的原因。

© www.soinside.com 2019 - 2024. All rights reserved.