Thread: 2D Array's, assigning chars.

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    6
    Sorry, I actually didn't copy the code from the program, I just rushed it quickly. This is how it was:

    Code:
    #define ROWS 5
    #define COLMNS 5
    
    char array[5][5];
    
    while(y < COLMNS) {
       fgets(array[i], ROWS, stdin);
       i++;
       y++  ;
    }
    Yeah the second example is quite stupid, but what I want is just the user to enter input, hitting return for a new line(I'm actually trying to avoid using fgets to be honest). Example :

    Enter chars:
    1 . 4 a g
    1 2 3 4 5
    . . ! t x
    a b c d e
    5 4 3 2 1

    Your array is:
    1 . 4 a g
    1 2 3 4 5
    . . ! t x
    a b c d e
    5 4 3 2 1

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Maybe something like:
    Code:
    #define ROWS 5
    #define COLMNS 5
    
    char array[ROWS][COLMNS];
    char line[6];
    
    y = 0;
    while(y < ROWS) {
       fgets(line, sizeof line, stdin);
       memcpy(array[y], line, COLMNS);
       y++  ;
    }
    Or using getchar():
    Code:
    #define ROWS 5
    #define COLMNS 5
    
    char array[ROWS][COLMNS];
    int ch, r, c;
    
    for (r=0; r<ROWS; r++)
    {
       c = 0;
       while ((ch = getchar()) != '\n')
       {
          if (c < COLMNS) array[r][c++] = ch;
       }
    }
    Last edited by swoopy; 04-26-2008 at 02:13 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 06-10-2007, 05:54 AM
  2. 2D Arrays: Column/Row Order
    By Ashes999 in forum C++ Programming
    Replies: 1
    Last Post: 07-01-2003, 08:03 PM
  3. pointers to 2d arrays
    By Diamonds in forum C++ Programming
    Replies: 4
    Last Post: 10-31-2002, 06:58 AM
  4. Passing 2D arrays by reference
    By samGwilliam in forum C++ Programming
    Replies: 9
    Last Post: 04-27-2002, 12:20 PM
  5. 2D arrays with functions made easy
    By goran in forum C Programming
    Replies: 1
    Last Post: 09-17-2001, 12:08 PM