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

c 把txt文件读到二维数组-ag真人游戏

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

#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;
  }
}
网站地图