954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Two-Dimensional Array Return

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.

Possédé
Newbie Poster
2 posts since Apr 2011
Reputation Points: 10
Solved Threads: 0
 

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.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 
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.

Possédé
Newbie Poster
2 posts since Apr 2011
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: