0

quick question and maybe a simple one. I haven't coded in c++ for a good bit but I am making a small program for a friend. This program is just taking a text file and inputting it into a simple 2d Array.

The table or 2d array structure is as follows: 4 6 1 5 2 34 13 1 42 9 34 11 5 -1 12 8 20 1 25 0 9 6 17 23 5 1

Where the first number is the Rows and the second number is the Columns, then after those two numbers we get the actual table.

I am able to input the first two numbers correctly into the RowCount and ColumnCount but how would I go about getting the actual table into an array?

Here is what I have currently, I know I need to setup the array properly after I get the rowCount and colCount, but then after that how would I input the table into an array?

// Importing the information Function
void importTable(string filePath, int** &table, int &rowCount, int &colCount){

ifstream fileInput;
filePath = filePath + ".txt";
fileInput.open(filePath.c_str());

if(fileInput != NULL){
        fileInput >> rowCount;
        fileInput >> colCount;
        // Setup the Array
        for(int i = 0; i < rowCount; i++){
            table[i] = new int[colCount];
        }

        fileInput.close();

} else {
    cout << filePath << " is missing or does not exist, try again" << endl;
}
}

// Main Function
int main() {
int rowCount = 0;
int colCount = 0;
int **table;
table = new int*[rowCount];

int *rowCountP = &rowCount;
int *colCountP = &colCount;

string filePath = "";

cout << "Enter the filepath name: " << endl;
cin >> filePath;
cout << endl;

importTable(filePath, table, rowCount, colCount);
cout << rowCount << colCount;

return 0;
}
ChonBonStudios
  • 213
  • 4
  • 14

1 Answers1

0

Use an std::stringstream, and assign array elements by reading values from the stream.

You syntax will look very similar to How to split a space separated string into multiple strings in C++?, but you'll have to turn each string you read into a number (by using atoi(), for example).

Community
  • 1
  • 1
Kukanani
  • 718
  • 1
  • 6
  • 22