Thread: storing a pattern of characters into a 2D array

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    3

    storing a pattern of characters into a 2D array

    hello,

    i am tinkering with some code that stores a pattern of characters into an array of 20x60, found from the standard input stream (basically a text file with characters on eachline 20x60 at the end of each line is a line break). i cannot get the program to print the text file when i execute and redirect a text file to the executable. can anyone help me out or let me know of some suggestions in the code i can make?

    thanks!

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    #define    ROWS    20
    #define    COLS    60
    
    int main()
    {
      int i, j, r, c;   // indexers
      char cell[ROWS][COLS];   // the pattern
      char value; // from input stream
    
      for( r = 0; r < ROWS; ++r)
      {
        c = 0;
        while( (value = getchar() ) != '\n')
        { 
          cell[r][c++] = value;    // store X or O
        }
      }
      
      putchar('\n');
      
      for( i = 0; i < ROWS; ++i )
      {
        for( j = 0; j < COLS; ++j )
          putchar(cell[i][j]);
        putchar('\n');
      }
      putchar('\n');
    
      return 0;
    }

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    184
    looking at your code
    Code:
    while( (value = getchar() ) != '\n')
        { 
          cell[r][c++] = value;    // store X or O
        }
    you shouldn't use getchar() to read a char as it returns an int not the char. and more over you are not terminating the string any where in the program after geting the string from the user. probably it might display you some junk valeus if you dont do that.

    try to insert a NULL('\0') after storing the values in the string
    Code:
    cell[r][c]='\0';


    s.s.harish

  3. #3
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    You're also not checking for EOF, but you should be.
    If you understand what you're doing, you're not learning anything.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. 2D array of threads?
    By shorinhio in forum C Programming
    Replies: 2
    Last Post: 01-04-2007, 04:02 PM
  2. Copying from one 2d array to another....with a twist
    By Zildjian in forum C++ Programming
    Replies: 2
    Last Post: 10-24-2004, 07:39 PM
  3. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM
  4. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM
  5. 2d Array access by other classes
    By deaths_seraphim in forum C++ Programming
    Replies: 1
    Last Post: 10-02-2001, 08:05 AM