Trouble storing file input in array

This is a discussion on Trouble storing file input in array within the C Programming forums, part of the General Programming Boards category; I'm using the following to read a 3 line by 3 column file and storing it into the array. However, ...

  1. #1
    Registered User
    Join Date
    Sep 2004
    Posts
    16

    Trouble storing file input in array

    I'm using the following to read a 3 line by 3 column file and storing it into the array. However, when I try to print out the array contents, only the first line is correct. The rest is either gibberish smiley faces or sometimes numbers.

    Code:
       char read, array[3][3];
       int i=0, j=0;
    
       FILE *test = fopen("test.txt","r");
       while (!feof(test))
       {
          fscanf(test, "%c", &read);
          if (read=='\n')
             break;
          else
             array[i][j]=read;
          if (i<3 && j<3)
             j++;
          else if (i<3 && j==3)
             i++;
       }

  2. #2
    Registered User
    Join Date
    Oct 2004
    Posts
    11
    if (read=='\n')
    break;
    This code will break out of your read loop after the first line is read in. This will cause only 1 line to be read. The data inside the other parts of your array are junk characters because they weren't initialized.

    for example you might have the file be something like:

    abc
    123
    xyz

    you code will read in abc and then detect a newline('\n') and break.

    You may try:
    Code:
    while (!feof(test))
    {
       fscanf(test, "%c", &read);
       if (read=='\n')
       {
          j = 0;  //reset j
          i++;   //increase to next line
          continue;  //go back to top of loop
       }
       j++;
    }
    hope this helps,
    Ryan

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need Help Fixing My C Program. Deals with File I/O
    By Matus in forum C Programming
    Replies: 7
    Last Post: 04-29-2008, 08:51 PM
  2. Trouble with file input
    By w274v in forum C Programming
    Replies: 6
    Last Post: 12-18-2005, 04:40 AM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 09:39 AM
  4. Reading strings from a file and storing into an array
    By Rizage in forum C++ Programming
    Replies: 1
    Last Post: 10-24-2002, 04:04 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21