How To Read integers from a text file to a multidimentional array.

Discussion in 'C' started by Programming_Kills, Nov 10, 2010.

  1. Programming_Kills

    Programming_Kills New Member

    Joined:
    Jun 14, 2010
    Messages:
    19
    Likes Received:
    0
    Trophy Points:
    0
    Hi EveryOne.
    i am Learnng C hence it is not a part of my course but i am trying to learn it.
    i am reading a file which contains integers.
    for example.
    12345637
    32423423
    34234233
    34234234
    43242343
    65765767
    65858688
    87078787

    and i want to load the same file into A 8x8 array.
    so can anyone plz help me out.
    Thanks in Advance
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    Something like this maybe?
    Code:
    void test33()
    {
    	int arr[8][8];
    	int x=0, y=0;
    	FILE *fp;
    	if (!fopen_s(&fp,"C:\\_xfr\\numbers.txt","r"))
    	{
    		while (!feof(fp))
    		{
    			int c=fgetc(fp);
    			if (c>='0' && c<='9')
    			{
    				arr[x][y]=c-'0';
    				x++;
    				if (x>7)
    				{
    					x=0;
    					y++;
    					if (y>7)
    						break;
    				}
    			}
    		}
    		fclose(fp);
    	}
    	for (y=0; y<8; y++)
    	{
    		for (x=0; x<8; x++)
    		{
    			printf("%d ",arr[x][y]);
    		}
    		printf("\n");
    	}
    }
    
    Output:
    1 2 3 4 5 6 3 7
    3 2 4 2 3 4 2 3
    3 4 2 3 4 2 3 3
    3 4 2 3 4 2 3 4
    4 3 2 4 2 3 4 3
    6 5 7 6 5 7 6 7
    6 5 8 5 8 6 8 8
    8 7 0 7 8 7 8 7
     
  3. Programming_Kills

    Programming_Kills New Member

    Joined:
    Jun 14, 2010
    Messages:
    19
    Likes Received:
    0
    Trophy Points:
    0
    Thank you very MUch xpi0t0s.
    May Allah Almighty Bless You.
     
  4. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    He does, frequently, although I know him as Jesus. xpi0t0s is derived from his name in Greek (christos).
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice