将值从文件添加到双指针

add value from file to double pointer

本文关键字:指针 添加 文件      更新时间:2023-10-16

my .h 文件

#ifndef ADJACENCYMATRIX_H_
#define ADJACENCYMATRIX_H_
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
using namespace std;

class AdjacencyMatrix{
private:
    int vertexCount;
    int vertexFirst;
    int edgeCount;
    int **wage;
    int **matrix;
public:
    AdjacencyMatrix();
    virtual ~AdjacencyMatrix();
    bool createFromFile(string path);
    void viewMatrix();

};
#endif /* ADJACENCYMATRIX_H_ */

我读取了表单文件,我想将其写入初始化的矩阵,但它不起作用。你可以帮我吗?

#include "AdjacencyMatrix.h"
AdjacencyMatrix::AdjacencyMatrix() {
    this->vertexCount=0;
    this->vertexFirst=-1;
    this->edgeCount=0;       
}
AdjacencyMatrix::~AdjacencyMatrix() { }
bool AdjacencyMatrix::createFromFile(string path) {
    fstream file;
    file.open(path.c_str(), fstream::in);
    if (file.good())
    {
        int vertexF,vertexE,wag;
        cout << "file opened" << endl;
        file >> this->edgeCount;
        file >> this->vertexCount;
        file >> this->vertexFirst;
        matrix = new int *[edgeCount];
        wage = new int *[edgeCount];
        for (int i = 0; i < vertexCount; i++)
        {
            matrix[i]=new int[edgeCount];
            wage[i]=new int[edgeCount];
        }
        //fill matrix by zeros
        for (int i = 0; i < vertexCount; i++)
        {
            for(int j=0; j<edgeCount;j++)
            {
                matrix[i][j]=0;
                wage[i][j]=0;
            }
        }
        // fill matrix by 1
        for(int i=0; i<edgeCount; i++)
        {
            file >> vertexF >> vertexE >> wag;
            cout << " w " << wag;
            matrix[vertexF][vertexE] = 1;
        }
        file.close();
        return true;
    }
    cout << "File does not opened" << endl;
    return false;
}
void AdjacencyMatrix::viewMatrix(){
    cout << " Adjacency Matrix ";
    for(int i=0; i<vertexCount; i++)
    {
            for(int j=0; i<edgeCount;i++) {  
                cout << this->matrix[i][j] << " ";
            }
            cout<< endl;
    }
}

并且这部分不起作用(我的意思是,什么都没有显示,showMatrix() 不起作用)。我想从文件中获取值,然后将其编写为matrix[x][y] = 1因为我想创建一个图形路径。

for(int i=0; i<edgeCount; i++)
{
    file >> vertexF >> vertexE >> wag; // cout work in this line 
    matrix[vertexF][vertexE] = 1; // does not work 
}

矩阵的大小是错误的:

matrix = new int *[edgeCount]; // wrong size
wage = new int *[edgeCount];   // wrong size
for (int i = 0; i < vertexCount; i++)
    {
        matrix[i]=new int[edgeCount];
        wage[i]=new int[edgeCount];
    }

定义矩阵时,应改用vertexCount,如下所示:

matrix = new int *[vertexCount];
wage   = new int *[vertexCount];

这可能会导致分段错误或奇怪的行为。

此外,当您读取用户提供的数据时,您应该验证它们:

file >> vertexF >> vertexE >> wag;
matrix[vertexF][vertexE] = 1;

你确定vertexFvertexE不比vertexCount - 1edgeCount - 1大吗?