Thread: Reading integers from a File into an Array

  1. #1
    Registered User
    Join Date
    Apr 2006
    Posts
    9

    Reading integers from a File into an Array

    Hey,

    Basically for this question, I am reading elements of a matrix from a text file. Now, the matrix is an upper triangular matrix, meaning the elements under the main diagnol are zero.

    eg

    1 2 3 4
    0 5 6 7
    0 0 9 1
    0 0 0 2


    Heres the problem. In the text fle, the matrix is stored in "efficient form," meaning the anything below the main diagnol (the zeros) are not listed.

    Now I am trying the read in the efficient matrix text file and display it on the screen WITH the zeros added in. (It is a 6 x 6 matrix in the txt file btw) I have my algorithm...
    i = the zero counter (intialized to 0)
    j = the integer element counter (intialized to 6)

    -print the number of zeros in the i counter (i = 0)
    -increment the i counter (i = 1)
    -print the number of elements in the j counter from the text file (j = 6)
    -decrement the j counter (j =5)
    - new line

    -print the number of zeros in the i counter (i = 1...print 1 zero)
    -increment the i counter (i = 2)
    -print the number of elements in the j counter from the text file ( j = 5... print the next 5 elements)
    -decrement the j counter (j = 4)
    - new line

    ....and so on (the i and j variables dont match my code exactly...)

    I think my code is correct except for the part of reading in the text file in the element[] array (in bold below). Im not too sure on how to do that. If you could help me out with that, Id really apprecieate it!

    Thanks

    Code:
    #include<stdio.h>
    #include <stdlib.h>
    
    viewM1();
    
    main()
    
    {
    	int choice;
    
    	printf("\nThis program allows you to multiply two matricies in a NON-EFFICIENT format\n\n");
    	printf("Please choose from one of the following options:");
    	printf("\n1 - See Matrix #1");
    	printf("\n2 - See Matrix #2");
    	printf("\n3 - Multiply Matrix #1 and Matrix #2");
    	printf("\n4 - Exit\n");
    	printf("\nOption Number: ");
    
    	scanf("%d", &choice);
    
    	if (choice == 1)
    		viewM1();
    
    return 0;	
    }
    
    
    viewM1()
    {
    	int elements[22], i, j, k, l, counter = 0, a = 0;
    	FILE *file_ptr;
    	file_ptr = fopen("matrixA.txt", "r");
    	if (file_ptr == NULL)
    		{
    		printf("Sorry! The File could not be opened!\n");
    		exit(1);
    		}
    	else
    		{
    		while (!feof(file_ptr))
    		fscanf(file_ptr, "%d", &elements[a]);
    		a = a + 1;
    		}
    		
    			for (i = 0; i <= 5; i++)
    			{
    				for (j = 0; j < i; j++)
    				{
    					printf("0");
    
    					for (k = 6; k > 0; k--)
    					{
    						for (l = 0; l <= k; l++) 
    						{
    							printf("%d", elements[counter]);
    							counter++;
    						}
    					}
    				}
    					printf("\n");
    			}
    
    		
    
    
    		
    
    	fclose(file_ptr);
    	return 0;
    }

  2. #2
    Registered User
    Join Date
    Jun 2006
    Posts
    75
    Quote Originally Posted by bobby19

    Code:
    while (!feof(file_ptr))
    		fscanf(file_ptr, "%d", &elements[a]);
    		a = a + 1;
    
    Where are the braces of while?

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    9
    Whoops...ahhh totally forgot them.

    Added them in, but still wild results coming out...Is that the proper way to read the elements into the array?

    Thanks

  4. #4
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    Code:
    while (!feof(file_ptr))      /* http://c-faq.com/stdio/feof.html */
       fscanf(file_ptr, "%d", &elements[a]);
       a = a + 1;      /* what is the role of a? */
    > int elements[22],
    Furthermore, by my count your text file has 21 numbers in it. Assuming that a row in a six-by-six matrix has six numbers, there is no way (efficient or not) that 21 numbers fills half the matrix. 21 doesn't even have six as a factor.

    [edit]
    Matrices must be my one true weakness.
    Last edited by whiteflags; 10-08-2006 at 12:42 AM.

  5. #5
    Registered User
    Join Date
    Apr 2006
    Posts
    9
    -15 1 -12 -2 -2 3
    0 -9 -12 -4 -14 -11
    0 0 -13 10 -14 -2
    0 0 0 10 -1 -2
    0 0 0 0 6 5
    0 0 0 0 0 -11


    That would be the matrix in full form. The 21 elements in the text file are basically 6^2 - 15.

    ahh its not showing up properly...but that is the format

  6. #6
    Registered User
    Join Date
    Jun 2006
    Posts
    75
    You're printing it wrongly. Try using:
    Code:
    	for (i = 0; i <= 5; i++)
    	{
    		for (j = 0; j < i; j++)
    		{
    			printf("%4d ", 0);
    		}
    		
    	
    		for ( ; j<=5; j++)
    		{
    			printf("%4d ", elements[counter]);
    			counter++;
    		}
    		
    		printf("\n");
    	}

  7. #7
    Registered User
    Join Date
    Apr 2006
    Posts
    9
    Thank you!

  8. #8
    Reverse Engineer maxorator's Avatar
    Join Date
    Aug 2005
    Location
    Estonia
    Posts
    2,318
    Quote Originally Posted by bobby19
    Whoops...ahhh totally forgot them.

    Added them in, but still wild results coming out...Is that the proper way to read the elements into the array?

    Thanks
    Now that's what happens when you don't put braces around one-line statements. Later you want to add one more line and you've got a problem.
    "The Internet treats censorship as damage and routes around it." - John Gilmore

  9. #9
    Registered User
    Join Date
    Apr 2006
    Posts
    9
    Hi again,

    1 more problem now....

    I changed the location of where the files are scanned into the main function so that I can pass the arrays on the matrix multiply function when need be. I also added in a 2D array which stores the enitre matrix (matrixA2D and matrixB2D - so that I can matrix multiply later on)

    When I enter option 1 to view Matrix 1, it goes to the 5th row of the array and abruptly stops and I get an error. I took out the operation where I fill in the elements for the 2D array, and then it works. Im not sure what the problem is though. Tracing through the code, it seems like what I have wrote will fill in the elements for the 2D array... Any thoughts?

    Code:
    #include<stdio.h>
    #include <stdlib.h>
    
    void viewM1(int [21]);
    void viewM2(int [21]);
    
    
    void main()
    
    {
    	FILE *file_ptrA;
    	FILE *file_ptrB;
    	int choice;
    	int elementsA[21], elementsB[21], counter = 0, a = 0, b = 0;
    
    	file_ptrA = fopen("matrixA.txt", "r");
    	file_ptrB = fopen("matrixB.txt", "r");
    
    	while (!feof(file_ptrA))
    			{	
    			fscanf(file_ptrA, "%d", &elementsA[a]);
    			a = a + 1;
    			}
    
    	while (!feof(file_ptrB))
    			{	
    			fscanf(file_ptrB, "%d", &elementsB[b]);
    			b= b + 1;
    			}
    
    	fclose(file_ptrA);
    	fclose(file_ptrB);
    
    
    	printf("\nThis program allows you to multiply two matricies in a NON-EFFICIENT format\n\n");
    	printf("Please choose from one of the following options:");
    	printf("\n1 - See Matrix #1");
    	printf("\n2 - See Matrix #2");
    	printf("\n3 - Multiply Matrix #1 and Matrix #2");
    	printf("\n4 - Exit\n");
    	printf("\nOption Number: ");
    
    	scanf("%d", &choice);
    
    	if (choice == 1)
    		viewM1(elementsA);
    	else if (choice == 2)
    		viewM2(elementsB);
    }
    
    
    void viewM1(int matrixA[])
    {
    	int i, j, counter = 0, a= 0, matrixA2D[6][6];
    		
    	for (i = 0; i <= 5; i++)
    	{
    		for (j = 0; j < i; j++)
    		{
    			printf("%4d ", 0);
    			matrixA2D[i][j] = 0;
    		}
    		
    	
    		for (; j <= 5; j++)
    		{
    			printf("%4d ", matrixA[counter]);
    			matrixA2D[i][counter] = matrixA[counter];
    			counter++;
    		}
    		
    		printf("\n");
    		
    	}
    
    }
    
    
    void viewM2(int matrixB[])
    {
    	int i, j, counter = 0, a = 0, matrixB2D[6][6];
    
    		
    	for (i = 0; i <= 5; i++)
    	{
    		for (j = 0; j < i; j++)
    		{
    			printf("%4d ", 0);
    			matrixB2D[i][j] = 0;
    		}
    		
    	
    		for (; j<=5; j++)
    		{
    			printf("%4d ", matrixB[counter]);
    			matrixB2D[i][counter] = matrixB[counter];
    			counter++;
    		}
    		
    		printf("\n");
    	}
    		
    }

  10. #10
    Registered User
    Join Date
    Oct 2004
    Posts
    151
    main() returns int. See site FAQ.
    Don't use feof() to control while loops. See site FAQ.
    You should check that the return value of fopen() isn't NULL.
    Last edited by zx-1; 10-08-2006 at 04:21 PM.
    System: Debian Sid and FreeBSD 7.0. Both with GCC 4.3.

    Useful resources:
    comp.lang.c FAQ | C++ FQA Lite

  11. #11
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    And then ensure that you access your array only within its bounds.
    Code:
    		for (; j <= 5; j++)
    		{
    			printf("%4d ", matrixA[counter]);
    			matrixA2D[i][counter] = matrixA[counter];
    			counter++;
    		}
    If you get to 10 or so in matrixA, where are you in matrixA2D? Perhaps you meant matrixA2D[i][j].
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  12. #12
    Registered User
    Join Date
    Apr 2006
    Posts
    9
    Prob Fixed! Thanks a lot for the tips and suggestions. Quick questions about the main function. Our text frequently uses the void return type for main. Is there a specific reason to have an int return type, and then return 0?

    Thanks again

  13. #13
    Registered User
    Join Date
    Oct 2004
    Posts
    151
    main() always returns int, except in very rare and very exceptional circumstances.
    Your textbook is made of fail.
    There are a few existing threads with further details.
    System: Debian Sid and FreeBSD 7.0. Both with GCC 4.3.

    Useful resources:
    comp.lang.c FAQ | C++ FQA Lite

  14. #14
    Registered User
    Join Date
    Mar 2006
    Posts
    725
    Quote Originally Posted by citizen
    Furthermore, by my count your text file has 21 numbers in it. Assuming that a row in a six-by-six matrix has six numbers, there is no way (efficient or not) that 21 numbers fills half the matrix. 21 doesn't even have six as a factor.
    Simple maths. For each diagonal the number of elements are:
    1 + 2 + 3 + 4 + 5 + 6
    >> 1 + 2 + ... + n-1 + n
    = n(n+1)/2.
    6(6+1)/2 = 21.


    By the way, using "x <= 5" in terms of iteration is less clear than using "x < 6". You could then make it more robust by subsituting "x < MATRIX_SIZE" in the future (or even right now, for readability).

    You want more compactness? You could use a single char for two digits (direct to binary or translating to valid ASCII characters), and maybe use the highest bit to store the sign. Whazaa.
    Code:
    #include <stdio.h>
    
    void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){
    puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9
    /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i]
    ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][
    t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading int's from file to array HELP plz
    By GARiMTO in forum C Programming
    Replies: 3
    Last Post: 12-14-2007, 06:12 AM
  2. Replies: 5
    Last Post: 10-02-2005, 12:15 AM
  3. reading from file to an array - help needed!
    By timeforheroes in forum C Programming
    Replies: 2
    Last Post: 04-28-2005, 12:16 PM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. Reading Characters from file into multi-dimensional array
    By damonbrinkley in forum C Programming
    Replies: 9
    Last Post: 02-24-2005, 01:31 PM