Having troubles reading in file to array

This is a discussion on Having troubles reading in file to array within the C Programming forums, part of the General Programming Boards category; Code: #include<stdio.h> #include<math.h> #define NROWS 8 #define NCOLS 7 int main (void) { FILE *input; int i; int j; double ...

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    48

    Having troubles reading in file to array

    Code:
    #include<stdio.h>
    #include<math.h>
    #define NROWS 8
    #define NCOLS 7
    int main (void)
    {
    	FILE *input;
    	int i;
    	int j;
    	double power[NROWS][NCOLS];
    
    	input=fopen("power1.dat", "r");
    	if(input==NULL)
    		printf("Error opening input file. \n");
    	else
    	{
    		for(i=0; i<NCOLS; i++)
    			for(j=0; j<NCOLS; j++)
    				printf("i is %d, j is %d with value %lf", i, j, power[i][j]);
    	}
    	return 0;
    }
    My i and js work fine but i dont get the right value for power[i][j], can anybody see anything wrong with it

  2. #2
    Registered User
    Join Date
    Oct 2008
    Posts
    48
    to make my self more clear in power[0][0] the value should be 253 but instead i get 0.0000000000

  3. #3
    Registered User
    Join Date
    Oct 2008
    Location
    TX
    Posts
    2,057
    You need fscanf() to read the double value from the file into the 2D array power.

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    I'm posting while doing a few other things, which is always risky, and it's untested, but I
    think you can get the general idea, at least.

    Code:
    int r, c, maxRows, maxCols, gotit;
    
    for(r = 0; i < maxRows; r++)   {
       for(c = 0; c < maxCols; c++)  {
             gotit = fscanf(in, "%d", data[r][c]);   //could be &data[r][c], so check that
             if(gotit < 1)
                goto done; 
       } 
    }
    done:
    ;
    //labels (like done, here), may require a semi-colon on the next line

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 12-08-2008, 10:27 AM
  2. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-22-2008, 12:19 AM
  3. Reading all the numbes from a file and storing in an array
    By derek tims in forum C++ Programming
    Replies: 2
    Last Post: 04-02-2006, 04:01 PM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 07:39 AM
  5. Reading strings from a file and storing into an array
    By Rizage in forum C++ Programming
    Replies: 1
    Last Post: 10-24-2002, 04:04 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21