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;

}

1
  • 2
    What are you not getting right? What is wrong with your code? This might help: stackoverflow.com/questions/1120140/…. It is about reading csv files, but it has quite complete answers where you can replace the seperator Commented Sep 3, 2021 at 8:57

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.