菜鸟笔记
提升您的技术认知

C++把txt文件读到二维数组

两个函数,一个已知文件的行和列,一个不知道行和列,看函数名就清楚了

#include <iostream>
#include <fstream>

using namespace std;

#define MAX_NODE 100

int n1, n2; // 分别表示矩阵的行和列


int main(int argc, char* argv[]){

    int** readTxtToArrayKnowRowAndColumn(const char* strPath, int m, int n);

    int** readTxtToArrayWithoutKnowRowOrColumn(const char* strPath);

    void printArray(int **a, int m, int n);

    cout << "read data" << endl;

    // int** m = readTxtToArrayKnowRowAndColumn("m1.txt", 9, 9); // 假设知道文件的行数和列数

    int** m = readTxtToArrayWithoutKnowRowOrColumn("m1.txt");     

    cout << "行数: " << n1 << ", 列数: " << n2 << endl;
    printArray(m, n1, n2);

    return 0;
}


int** readTxtToArrayWithoutKnowRowOrColumn(const char* strPath){
    int** a = new int* [MAX_NODE];
    for(int i = 0; i < MAX_NODE; i++){
        a[i] = new int[MAX_NODE];
    }
    int nTmp = 0;
    n1 = 0;
    n2 = 0;
    ifstream is(strPath);
    if(!is){
        cout << "open file error!" << endl;
    }else{
        char p;
        int num;
        int j = 0;
        while(is.get(p)){ // 判断是否到达文末
            do{
                if(p == '\n'){
                     n1++; // 统计行数
                     if(n2 == 0){
                         n2 = nTmp; // 实际上只统计了第一行的列数
                     }
                     j = 0;
                     // cout << endl; // 一行之后输出一个回车符
                }
            }while(isspace((int)p) && is.get(p));
            if(!is)
                break;
            nTmp++; // 统计列数
            is.putback(p); // 如果前面读入的不是空格或者回车符,则把刚才读入的字符返回文件流
            is >> num;
            // cout << num << "\t";
            a[n1][j++] = num;
        }     
    }
    is.close();
    return a;
}

int** readTxtToArrayKnowRowAndColumn(const char* strPath, int m, int n){
    int** a = new int* [MAX_NODE];
    for(int i = 0; i < MAX_NODE; i++){
        a[i] = new int[MAX_NODE];
    }
    ifstream is(strPath);

    for(int i = 0; i < m; i++){
        for(int j = 0; j < n; j++){
            is >> a[i][j];
        }
    }

    n1 = n2 = 9;

    is.close();
    return a;
}

void printArray(int** a, int m, int n){
  for(int i = 0; i < m; i++){
    for(int j = 0; j < n; j++){
      cout << a[i][j] << "\t";
    }
    cout << endl;
  }
}