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

有一部分参考了这篇文章:http://lzh0859.blog.sohu.com/43892352.html,就是判断文件结束有问题查阅教材进行了调整,感谢

两个函数,一个已知文件的行和列,一个不知道行和列,看函数名就清楚了
其中,m1.txt存放距离矩阵,内容见我的另一篇博客:http://blog.csdn.net/u013527937/article/details/53738352

#include 
#include 

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;
  }
}

你可能感兴趣的:(C++,自己看)