Tuesday, July 28, 2009

C++ Programming help! how do i fill in an array from a file on the computer? PLEASE READ DESCRIPTION AS WELL!?

ok, so for my computer science class i need to input an array from a file that already has the array. the file has on the first like two numbers, the number of rows in the array and then the number of columns in the array





after that, the file has 10 rows and 5 columns, and each point in the array is either a '0' or a '1'





i need to write a void function that will just take in the array. not display it or anything, but just to take in the array.





my TA said to first declare the array in 'main' and then in the funciton called 'getfromfile' to input the numbers of the array into the array.





if anyone can help me out here that would really mean a lot





and keep in mind, im using C++, nothing else. if you write stuff thats not in C++ i'm going to have no idea what your writing and its just going to confuse me, this is my first computer science class

C++ Programming help! how do i fill in an array from a file on the computer? PLEASE READ DESCRIPTION AS WELL!?
#include %26lt;iostream%26gt;


#include %26lt;string%26gt;


#include %26lt;fstream%26gt;





using namespace std;





void getfromfile(string fileName, int**%26amp; matrix, int%26amp; rows, int%26amp; columns);





int main()


{


int** matrix = NULL;


int rows = 0;


int columns = 0;


string fileName;





cout %26lt;%26lt; "Enter the name of the data file: ";


cin %26gt;%26gt; fileName;





getfromfile(fileName, matrix, rows, columns);








// The following lines of code need to be the last lines within


// main because they destroy (delete) the dynamic array we


// created above.


for(int i = 0; i %26lt; rows; i++)


{


delete[] matrix[i];


}


delete[] matrix;


return 0;


}





void getfromfile(string fileName, int**%26amp; matrix, int%26amp; rows, int%26amp; columns)


{


ifstream inFile;





inFile.open(fileName.c_str());


if(inFile.fail())


{


cout %26lt;%26lt; "Opening file failed!!" %26lt;%26lt; endl;


exit(1);


}





inFile %26gt;%26gt; rows %26gt;%26gt; columns;


matrix = new int*[rows];


for(int i = 0; i %26lt; rows; i++)


{


matrix[i] = new int[columns];


}





for(int i = 0; i %26lt; rows; i++)


{


for(int j = 0; j %26lt; columns; j++)


{


inFile %26gt;%26gt; matrix[i][j];


}


}





inFile.close();


}
Reply:you need to use these instructions:





#include %26lt;fstream%26gt;





//your code here





ifstream in("file_name");





then you can use the in object just as cin, i guess you know how to use it


No comments:

Post a Comment