Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   How to read unknown total of int data from text file to a 2-dim array in C++? (http://www.programmingforums.org/showthread.php?t=5823)

ladyscarlet99 Sep 9th, 2005 12:36 AM

How to read unknown total of int data from text file to a 2-dim array in C++?
 
I want to create a function read data of type int from a text file and stores them in a 2-dimensional array. But the number of the data in the text file is unknown during the program execution. Therefore the size of the array is also unknown.

I have problems in reading the correct data value of type int and stores them in the array. I also can't determine the correct total of columns and rows for the array.

My data in the text file looks something like this:

1111111111111111111
1000101010101010101
1010101010101011111
1111111111111111111
1011110000111111111
1111111111111111111

My coding is as below:
Code:

#define ROWMAX 100
#define COLMAX 100

int data[ROWMAX][COLMAX];
int ROW=0,COL=0;

void readdata(FILE *file,int data[ROWMAX][COLMAX])
{
int c;
int row=0,column=0,i,j;
int temp[ROWMAX][COLMAX];

while(!feof(file))
{
fscanf(file,"%d",&c);
if (c!='\n' )
{
temp[i][j]=c;
//printf("%d",temp[i][j]);
column=column+1;

}
else
{ //printf("\n");
column=0;
row++;
}//end if

} //end while

ROW=row+1;
COL=column-1;

printf("\nSize of array = [%d] x [%d]\n",ROW,COL);

//display data
for(i=0;i<ROW;i++)
{
for(j=0;j<COL;j++)
{
data[i][j]=temp[i][j];
printf("%1.4f",data[i][j]);
}

printf("\n");
}

Does anyone knows the easiest solution to this? Please give me any source code examples for reading data of type int in text file during run time and determining the total of rows and columns for the arrays?

Later, I need to scan each row of data for 0s and stores them in text file.then I access the text file to normalize all 0s by rows. Therefore I need to save the information about the location of the 0s(which rows and columns).After the normalization,I need to replace the 0s in the later text file with the new value at the correct location. How to save the location value(rows and pixels) and corresponds them with their new normalized value?

Thanks in advance.

BinaryStorm Sep 9th, 2005 1:00 AM

If the size is unknown, it is best to use vectors. Vectors are resizeable.
So you can simply create vector of type int, and store file contents there.
:

#include <vector>
using std::vector;
.
.
.

vector <int> data;
for (int i=0; i<sizeof (pointerToText); i++)
{
    data[i] = something;
}


iignotus Sep 9th, 2005 1:01 AM

Do not double post and use [ CODE ] tags and repost your message.


All times are GMT -5. The time now is 5:07 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC