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

标签 c++ exception character fileinputstream double-pointer

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

最佳答案

做正确的事

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

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

关于c++ - 在 2D 指针和重新生成中从文件输入字符时出现异常错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52342173/

相关文章:

c++ - CPP 中没有构造函数错误的实例

java - 错误和异常有什么区别?

C++ 将八个 boolean 值压缩为一个字符

java - isDigit() 为字母返回 true

java - Checked Exception 2种行为

r - 用cat()和paste()串联字符串之间有什么区别?

c++ - 为什么我们必须在复制构造函数的参数中使用引用而不是指针?

c++ - 如果我创建一个 list<T>::iterator,有没有办法重载++(增量)运算符?

c++ - 模板函数特化

exception - 如何实现基于Apache Thrift的golang服务有异常?