Thread: Reading Characters from file into multi-dimensional array

  1. #1
    Registered User
    Join Date
    Oct 2002
    Posts
    385

    Reading Characters from file into multi-dimensional array

    I'm having troubles reading characters from a file into a multi-dimensional array. I'm able to read them in but the output isn't correct when displaying the characters in the array. This is for a wordfind program and I need to read each letter of the puzzle into a spot in a multi-dimensional array and I can do some comparisons to see if a word exists in the puzzle. Here's my code for reading the characters into the array.

    Code:
    #include <stdio.h>
    
    int main()
    {
    	int i, j, c, row, col;
    	FILE *fp;
    
    	row = col = 15;
    	
    	fp = fopen("cashiers.txt", "r");
    
    	// read letters into array
    
    	char array[row][col];
    
    	for (i = 0; i <= row - 1; i++)
    			for (j = 0; j <= col - 1; j++)
    				array[i][j] = ' ';
    
    	while ((c = getc(fp)) != EOF)
    	{
    		for (i = 0; i <= row - 1; i++)
    			for (j = 0; j <= col - 1; j++)
    				if((c != '\n') && (c != '\r'))
    					array[i][j] = c;
    	}
    	
    
    	for(i = 0; i <= row - 1; i++)
    	{
    		for(j = 0; j <= col - 1; j++)
    			printf("%c", array[i][j]);
    		printf("\n");
    	}
    
    	return 0;
    }
    Thanks for any help you can offer.
    Last edited by damonbrinkley; 02-24-2005 at 10:08 AM.
    Wandering aimlessly through C.....

    http://dbrink.phpwebhosting.com

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    To me this looks like to many loops.
    Code:
    	while ((c = getc(fp)) != EOF)
    	{
    		for (i = 0; i <= row - 1; i++)
    			for (j = 0; j <= col - 1; j++)
    				if((c != '\n') && (c != '\r'))
    					array[i][j] = c;
    	}
    For each character you read, you assign it to the entire array.

    It might be helpful to post "cashiers.txt".
    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.*

  3. #3
    Registered User
    Join Date
    Oct 2002
    Posts
    385
    Here is cashiers.txt

    Code:
    DNOPSNOITACAVFX
    BSERENITYNZEKYI
    ZBREAMOANARHECM
    BBASSWGITOOLKAY
    QSCENERYTNLCYMM
    TUORTIASEAUBDPA
    JZIVVVYYVDXOWSE
    FSSENREDLIWAMIR
    FIRSEHRSPNLTLTT
    CLSCUILRTLYKAES
    XAOHQKFOEFYLUSR
    ORBGIIWYDSAQLEM
    GEYITNEFPGOROEA
    EKALNGGAXRERCGJ
    TEKRAMSGCAFETOY
    Wandering aimlessly through C.....

    http://dbrink.phpwebhosting.com

  4. #4
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    My usual compiler is not C99, so forgive the C90 mods. How about something like this?
    Code:
    #include <stdio.h>
    
    int main()
    {
       char array[15][15];
       int i = 0, j = 0, row = 15, col = 15;
       FILE *fp = fopen("cashiers.txt", "r");
       if ( fp )
       {
          for ( ;; )
          {
             int c = getc(fp);
             if ( c == EOF )
             {
                break;
             }
             if ( c != '\n' && c != '\r' )
             {
                array[i][j] = c;
                if ( ++j >= col )
                {
                   j = 0;
                   if ( ++i >= row )
                   {
                      break;
                   }
                }
             }
          }
          fclose(fp);
       }
       for ( i = 0; i < row; i++ )
       {
          for ( j = 0; j < col; j++ )
          {
             putchar(array[i][j]);
          }
          putchar('\n');
       }
       return 0;
    }
    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.*

  5. #5
    Registered User
    Join Date
    Oct 2002
    Posts
    385
    Thanks Dave, that worked. I can't figure out what is different about what you did and what I did but your works. I've now tried to put that piece into my progressing code and I'm getting the same problem that I got before. When I output the contents of the array to stdout I get a bunch of jumbled signs as output.

    Here's my code:
    Code:
    #include <stdio.h>
    
    int main()
    {
    	int c, i, j, row, col, nl, cr;
    	
    	row = col = nl = cr = 0;
    	
    	FILE *fp = fopen("cashiers.txt", "r");
    
    	// Figure out how many rows and columns the text file has
    	while ((c = getc(fp)) != EOF)
    	{
    		if (c == '\n')
    			nl++;
    		if (c == '\r')
    			cr++;
    		
    		col++;
    		
    		if (c == '\n')
    			row++;
    		
    		putchar(c);
    	}
    
    	col = (col - (nl + cr));
    	col = (int) (col/row);
    
    	printf("\nnumber of rows is %d\n", row);
    	printf("number of columns is %d\n\n", col);
    
    	
    	// read letters into array
    
    	char array[row][col];
    
    	if ( fp )
       	{
    		for ( ;; )
          		{
    			c = getc(fp);
             		if ( c == EOF )
             		{
                			break;
             		}
             		if ( c != '\n' && c != '\r' )
             		{
                			array[i][j] = c;
                			if ( ++j >= col )
                			{
                   				j = 0;
                   				if ( ++i >= row )
                   				{
                      				break;
                   				}
                			}
             		}
          		}
    		fclose(fp);
    	}
          	   
       	for ( i = 0; i < row; i++ )
       	{
          		for ( j = 0; j < col; j++ )
          		{
             		putchar(array[i][j]);
          		}
          		putchar('\n');
       	}
       	return 0;
    }
    And here's what I get as output:

    Code:
    DNOPSNOITACAVFX
    BSERENITYNZEKYI
    ZBREAMOANARHECM
    BBASSWGITOOLKAY
    QSCENERYTNLCYMM
    TUORTIASEAUBDPA
    JZIVVVYYVDXOWSE
    FSSENREDLIWAMIR
    FIRSEHRSPNLTLTT
    CLSCUILRTLYKAES
    XAOHQKFOEFYLUSR
    ORBGIIWYDSAQLEM
    GEYITNEFPGOROEA
    EKALNGGAXRERCGJ
    TEKRAMSGCAFETOY
    
    number of rows is 15
    number of columns is 15
    
            O=
     4" P" " 
    ww/w
    w  ?=    
    "     wl 1
    5           
    = 2w         
           w    
                
    w      " &
    w(ww   
    w    w..w
    w    @    
         " Fw
    " >wFw
    I feel that I'm doing something wrong with my variable types or something and that's why it's coming out like that.

    Once again, thanks for your help.
    Last edited by damonbrinkley; 02-24-2005 at 12:47 PM.
    Wandering aimlessly through C.....

    http://dbrink.phpwebhosting.com

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    #include <stdio.h>
    
    int main()
    {
    	int c, i, j, row, col, nl, cr;
    	
    	row = col = nl = cr = 0;
    	
    	FILE *fp = fopen("cashiers.txt", "r");
    
    	// Figure out how many rows and columns the text file has
    	while ((c = getc(fp)) != EOF)
    	{
    		if (c == '\n')
    			nl++;
    		if (c == '\r')
    			cr++;
    		
    		col++;
    		
    		if (c == '\n')
    			row++;
    		
    		putchar(c);
    	}
    
    	col = (col - (nl + cr));
    	col = (int) (col/row);
    
    	printf("\nnumber of rows is %d\n", row);
    	printf("number of columns is %d\n\n", col);
    
    	
    	// read letters into array
    
    	char array[row][col];
    
    	if ( fp )
       	{
    		for ( ;; )
          		{
    			c = getc(fp);
             		if ( c == EOF )
             		{
                			break;
             		}
             		if ( c != '\n' && c != '\r' )
             		{
                			array[i][j] = c;
    As of here, where have j and i been initialized? You're lucky your program runs at all.

    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    Registered User
    Join Date
    Oct 2002
    Posts
    385
    Thanks Quzah. I went back and initialized i and j at the start with the others but still get the same problem.
    Wandering aimlessly through C.....

    http://dbrink.phpwebhosting.com

  8. #8
    Registered User
    Join Date
    Oct 2002
    Posts
    385
    Ok, after doing some debugging with some printfs I figured out what was going on. Thanks for all the help.
    Wandering aimlessly through C.....

    http://dbrink.phpwebhosting.com

  9. #9
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by damonbrinkley
    I went back and initialized i and j at the start with the others but still get the same problem.
    After reading the file to the end to determine the rows and columns, rewind back to the beginning to read it.
    Code:
       char array[row][col];
    
       if ( fp )
       {
          rewind(fp);
          for ( ;; )
          {
    Last edited by Dave_Sinkula; 02-24-2005 at 01:25 PM. Reason: D'oh! Pokey again!
    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.*

  10. #10
    Registered User
    Join Date
    Oct 2002
    Posts
    385
    Quote Originally Posted by Dave_Sinkula
    After reading the file to the end to determine the rows and columns, rewind back to the beginning to read it.
    Code:
       char array[row][col];
    
       if ( fp )
       {
          rewind(fp);
          for ( ;; )
          {
    Thanks Dave. After doing some messing around I realized that was my problem. Thanks again.
    Wandering aimlessly through C.....

    http://dbrink.phpwebhosting.com

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 9
    Last Post: 12-08-2008, 10:27 AM
  2. Reading a list of ints from file into an array
    By mesmer in forum C Programming
    Replies: 1
    Last Post: 11-10-2008, 06:45 AM
  3. Replies: 1
    Last Post: 04-25-2006, 12:14 AM
  4. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  5. Text file to 2D Array PLEASE HELP!
    By lostboy101 in forum C Programming
    Replies: 0
    Last Post: 03-26-2002, 10:51 AM