0

Pleased I need help to read-in an ASCII file into a 2-dimensional integer array. I also want to automatically extract the number of columns and rows from the buffer. I am not getting something right for sure.

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

}

Syn Joseph
  • 11
  • 2
  • 2
    What are you not getting right? What is wrong with your code? This might help: https://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c. It is about reading csv files, but it has quite complete answers where you can replace the seperator – 463035818_is_not_an_ai Sep 03 '21 at 08:57

1 Answers1

2
int array[numrows][numcols]; //2-Dimensional array

The dimensions of an array must be known at compile-time. Variable-length array (VLA) are not supported in C++. Use a container with dynamic allocation instead, like 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);
    }
}

Print your whole array with

for (auto& line: array) {
    for (auto& el: line) {
        std::cout << el << ' ';
    }
    std::cout << '\n';
}

Or single elements with

std::cout << array[row][col];
// or array.at(row).at(col) to identify out-of-bound access more easily
m88
  • 1,968
  • 6
  • 14