# Thread: Data File in 2D Array

1. ## Data File in 2D Array

Hello,

I need help in assigning values in a 2D array to the 2nd set of elements. I'm opening a file that has rows and columns. I got the rows assigned to the 1st of elements, how do I assign the columns to the 2nd set.

I know this may be easy to most of you, but I don't know how to do it. I've searched on the internet, but I found nothing that helps. I know I need 2 loops for it.

Here's my code:

Code:
```dataCar=fopen("car.txt", "r");
{
while(  j < 8)
{
fgets(storeS,100,dataCar);
strcpy(ssheet[j],storeS);
j++;

while ( i < 10)
{

/* I'm not sure what to put here I tried the following */
ssheet[j][i]=0;
i++;

}
}```
An example line from a file looks like this:

Jaguar 80 82 81

So if that the 3rd row ssheet[2] how do I assign 80,82,81 to the columns?

2. You'll have to be more clear as to what you have a 2D array of. You can't have a 2D array that is simultaneously of strings ("Jaguar") and of ints (80).

3. Is it a fixed number of columns?
Code:
```for( row = 0; row < ROWS; row++ )
{
if( fscanf( file, "%s", name[ row ] ) != 1 )
{
printf( "encountered an error reading file\n" );
/* do something here */
}
else
{
for( col = 0; col < COLS; col++ ) /* technically we are reading column 1, not column 0 */
{
if( fscanf( file "%d", &number[ row ][ col ] != 1 )
{
printf( "error reading number [ %d ][ %d ]\n", row, col );
/* do something here */
}
}
}
}```
Now, in this example I am sticking the names from your first column into a different array than your numbers, which is why I said "technically we are reading column 1", but in the second array, it would fall as column 0, since arrays start at 0.

Quzah.

4. Yes, it is a fixed number of columns. I'll try that out, thanks.

Popular pages Recent additions