【问题标题】:How do I read Integer file into a 2 dimensional integer array in C++?如何在 C++ 中将整数文件读入二维整数数组?
【发布时间】:2021-11-01 14:34:27
【问题描述】:

很高兴我需要帮助才能将 ASCII 文件读入二维整数数组。 我还想自动从缓冲区中提取列数和行数。我肯定没有做对。

#include <iostream>
#include <fstream> 
#include <sstream> 

using namespace std;

int main() {
int row = 0, col = 0, numrows = 0, numcols = 0;

ifstream askeeFile ("asciiFile.dat");
stringstream sd;
int array[numrows][numcols]; //2-Dimensional array

sd << askeeFile.rdbuf();
sd >> numcols >> numrows; // I need to know the number of rows and columnn here
  


//Populating the 2-D array with the file content  
for(row = 0; row < numrows; ++row){
    for (col = 0; col < numcols; ++col){ sd >> array[row][col];
    
    askeeFile >> array[row][col];
    

    cout << array[row][col];
 
   
    }
         

}

  
askeeFile.close();
  

return 0;

}

【问题讨论】:

  • 你做错了什么?你的代码有什么问题?这可能会有所帮助:stackoverflow.com/questions/1120140/…。它是关于读取 csv 文件的,但它有相当完整的答案,您可以在其中替换分隔符

标签: c++ arrays file


【解决方案1】:
int array[numrows][numcols]; //2-Dimensional array

数组的维度必须在编译时知道。 C++ 不支持可变长度数组 (VLA)。改用动态分配的容器,例如std::vector

std::vector<std::vector<int>> array;
std::stringstream ss_file(data);
std::string line; 
while (std::getline(ss_file, line)) {
    array.push_back({});
    std::stringstream ss_line(std::move(line));
    int value;
    while (ss_line >> value) {
        array.back().push_back(value);
    }
}

打印整个数组
for (auto& line: array) {
    for (auto& el: line) {
        std::cout << el << ' ';
    }
    std::cout << '\n';
}

或单个元素与

std::cout << array[row][col];
// or array.at(row).at(col) to identify out-of-bound access more easily

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    相关资源
    最近更新 更多