c++ - 将文件中的数据分配给矩阵 C++

标签 c++ arrays file printing

大家好 我是 C++ 的初学者。 我想要达到的目标是愚蠢的。但我不明白/不明白错误在哪里。 我将非常感谢任何 bluecode 的帮助。

所以...我想分配文件“REL”的内容,它是一个46x2的矩阵[没有空行]:

28 28
28  6
28 21
28 30
28 16
22 22
22 33
22 9
39 39
39 32
39 46
39 10
39 24
36 36
36 7
36 43
36 23
11 11
11 26
11 41
15 15
15 17
15 45
15 29
15 40
3 3
3 37
3 42
3 34
3 2
35 35
35 4
35 14
35 44
35 18
13 13
13 12
13 25
13 5
13 1
13 8
13 31
20 20
20 27
20 19
20 38

我的 C++ 代码是:

    include <stdlib.h>
    include <malloc.h>
    include <iostream>
    include <fstream>

    using namespace std;

    void allocateMatrix(int **& A, int row, int col)
    {
        int i;
        A = new int*[row];
        for (i=1; i<=col; i++)
            A[i] = new int[col];
    }

    void ReadData(int **& A, int row, int col) // read data from file
    {  
    int i,j;
    ifstream REL1;
    REL1.open ("REL");  // open file for reading                
    for(i=1;i<=row;i++)   // row loop
    {
        for(j=1;j<=col;j++)  // column loop
        {
            REL1 >> A[i][j]; // read data into matrix
        }
        REL1.close(); // close the file                
    }
    }

    void Display(int **& A, int row, int col) // display matrix
    { 
    int i,j;
    for(i=1;i<=row;i++)
    {
        for(j=1;j<=col;j++)
        { 
            cout << A[i][j] << "\t ";  // display numbers
        }
        cout << endl;
    }    
    }

    void Cero(int **& A, int row, int col) // display matrix
    {
    int i,j;
    for(i=1;i<=row;i++)
    {
        for(j=1;j<=col;j++)
        {
            A[i][j]=0;
        }
    }   
    }   

    int main()
    {
    int tm,rowR,colR,rowM,colM,**A,**B; 

    ifstream TM;
    TM.open("TM");
    TM >> tm;
    TM.close();

    rowR = rowM = colM = tm;
    colR = 2;

    allocateMatrix(A, rowM, colM);
    allocateMatrix(B, rowR, colR);
    Cero(A, rowM, colM); 
    //Display(A, rowM, colM);
    ReadData(B ,rowR, colR);
    Display(B, rowR, colR);

    }

并且...当我在 bash 中运行它时,shell 提示我:

28   28  
0    0   
Segmentation fault (core dumped)

提前致谢!!!

最佳答案

for(i=1;i<=row;i++)   // row loop
{
    for(j=1;j<=col;j++)  // column loop
    {
        REL1 >> A[i][j]; // read data into matrix
    }
    REL1.close(); // close the file                
}

您将在阅读第一行后关闭文件。将文件结束行移出循环。

for(i=1;i<=row;i++)   // row loop
{
    for(j=1;j<=col;j++)  // column loop
    {
        REL1 >> A[i][j]; // read data into matrix
    }               
}
REL1.close(); // close the file 

关于c++ - 将文件中的数据分配给矩阵 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10669794/

相关文章:

python - 如何打开.npz文件

c++ - 为什么即使还有弱指针,make_shared 也会调用析构函数?

c++ - _commit 问题与 fd()

c++ - 计算值的总和

c - C 中不一致的 sizeof 行为

将字母 append 到文件末尾的 C 程序

c++ - con.txt 和 C++

c++ - BGL : Unable to access bundled vertex properties

javascript - 在数组中查找字符串

C 文件中的字符数