How to read a text file into an array

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Prisms
    New Member
    • May 2010
    • 3

    How to read a text file into an array

    I am trying to read a text file into an array and I'm having some trouble doing so. here is the code that I have so far. Any help would be much appreciated.

    Code:
    #include <stdio.h>
    #include <ctype.h>
    #define MAX_ROW 15
    #define MAX_COL 6
    
    
    int main()
    {
    	FILE* numbers;
    	int x;
    	int ary[MAX_ROW][MAX_COL];
    	
    	
    	numbers = fopen("extradata.txt", "r+");
    	
    	while (!feof(numbers))
    	{
    		fscanf(numbers, "%d", &x);
    		ary[MAX_ROW][MAX_COL] = x;
    	}
    	
    	fclose(numbers);
    	
    	for(int row; row<MAX_ROW; row++)
    	{
    		printf("\n");
    		
    		for(int col; col<MAX_COL; col++)
    		{
    			printf("%3d", ary[row][col]);
    		}
    	}
    	return 0;
    }
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    #2
    The same array element is being overwritten.
    That is element [MAX_ROW][MAX_COL] = x;

    You need to increment the rows and columns as you read the data in.

    Comment

    • Dheeraj Joshi
      Recognized Expert Top Contributor
      • Jul 2009
      • 1129

      #3
      Your while loop should change.
      Make changes as code green mentioned.

      Regards
      Dheeraj Joshi

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Protect yourself from text files that contain more numbers than will fit in the array.

        I don't use fscanf in my code, so I'm not familiar with it. Do successive calls to fscanf start scanning from the character that terminated the prior fscanf or do they start scanning from the start of the next line of text? I didn't find anything in the man pages that answered this question.

        Comment

        • Prisms
          New Member
          • May 2010
          • 3

          #5
          Originally posted by code green
          The same array element is being overwritten.
          That is element [MAX_ROW][MAX_COL] = x;

          You need to increment the rows and columns as you read the data in.
          Thanks I'll give it a try

          Comment

          Working...