Hello all, I am currently a student doing an end-of-year software project - and I need some help. I am currently trying to return a 2D array from a function contained in a header file. The function is called from the main() and asks the user to input the location of the excel (.csv) file on the hard drive. Upon correctly inputting the file location, the program assigns values from the file into an array. The code is as follows:

#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;


//function to read in the user specified file
 string Read() {

	string fileLoc, line, item;
	int lineNum = 0, i = 0, j = 0;
	string matrix[10][420];
	
	cout << "\nPlease enter the location of the file: ";
	cin >> fileLoc;

	ifstream inFile;
	inFile.open(fileLoc.c_str());

	if (!inFile) {
		cout << "\nError opening file... " << fileLoc << ". Please try again.\n" << endl;
		Read();
	}

	//assigns the matrix with values from the user specified file
	while(!inFile.eof()) {
		getline(inFile, line, ',');
		matrix[i][j] = line;
		/*cout << matrix[i][j] << ' ';*/
		if (i < 9) {i++;}
		if (i = 9) {i = 0;
		j++; }

	}
	return ?;
 }

The code above correctly takes the values stored in the excel file and inputs them into an array. What I am trying to understand is how to return the array so it can be used in other functions. I don't want to go down the pointers route if it can be avoided at all, as I'm not too competent at programming - but I'm always trying to become better!

If you need any more information please ask, any and all help will be much appreciated.

Recommended Answers

All 2 Replies

It would be unwise to return a local array. In my experience, the best solution is to accept the array as a parameter rather than try to return it.

It would be unwise to return a local array. In my experience, the best solution is to accept the array as a parameter rather than try to return it.

Okay, I changed the function to void and passed the array by reference. Seems to have done the trick. Thanks for your reply.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.