reading from a text file into a 2 Dimensional Array---JUNK VALUES!!??

This is a discussion on reading from a text file into a 2 Dimensional Array---JUNK VALUES!!?? within the C Programming forums, part of the General Programming Boards category; Hey everyone, So i have this bit of code here, and it reads values from a text file named sales.txt ...

  1. #1
    Registered User
    Join Date
    Jan 2013
    Location
    San Jose, CA
    Posts
    53

    Exclamation reading from a text file into a 2 Dimensional Array---JUNK VALUES!!??

    Hey everyone,

    So i have this bit of code here, and it reads values from a text file named sales.txt

    Code:
    #include <stdio.h>
    
    #define MAX_ROWS 25
    #define MAX_COLS 20
    
    int main()
    {
       FILE *fp = fopen("sales.txt", "r");
       char array[25][20];
       int i = 0;
       int j = 0;
       int row = 25;
       int col = 20;
    
       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;
    }
    the results I get when i run the program are these:

    Code:
    425 20 25 2520 22 23
     2225 26 25 2230 28
    25 2625 30 45 2030 2
    5 20 2127 25 24 2620
     23 24 2028 26 24 25
    30 10 35 3228 29 30
    3515 16 15 1412 15 1
    2 1920 24 20 1810 15
     12 1632 30 33 29aa-
    GCCLIBCYGMING-EH-TDM
    1-SJLJ-GTHR-MINGW32
    h$7 ⌐1@ ╚■( →@ t☺s
    ╕■( ╒qw♥   ☻  ☻☻
    ε<   p☺ q☻   ╪↨7
    h$aaaaaaaaaaAAaA
    x♫7 x♫7 ■( ⌠Au  7
        ⌠Au    x♫7 x♫7
    ■( ⌠Au  7     ⌠Au
    ▓╒▲♦   |♫7 x♫7 ╩w
    "►w    $   ■( ♦
        ╝V≈■(  Au
        ╚←@ ╝■( BAu☻Ku
    ⁿ■( ╥⌠A   ◄Bub◄Bu
    ╒▲    ╚←@     P↑@
    ╨■( ( ─ ( ╒Cur:╬k
    
    Process returned 0 (0x0)   execution time : 0.090 s
    Press any key to continue.
    why on earth am I getting weird symbols and junk values?!?!
    the sales.txt file has these contents:

    Code:
    4
    25 20 25 25
    20 22 23 22
    25 26 25 22
    30 28 25 26
    25 30 45 20
    30 25 20 21
    27 25 24 26
    20 23 24 20
    28 26 24 25
    30 10 35 32
    28 29 30 35
    15 16 15 14
    12 15 12 19
    20 24 20 18
    10 15 12 16
    32 30 33 29
    the 4 at the very top of the sales.txt file represents the number of weeks. this number (4) is then followed by the weekly sales for the salespeople listed in the sales.txt file.

    I also have another file that I try to read, it's called names.txt and its contents are:

    Code:
    16
    Kelly, Victor       
    Lam, Gary           
    Nagasake, David     
    Nguyen, Jeff        
    Nguyen, Michael     
    Sinn, Scott         
    Smith, Jacob        
    Son, Thai           
    Tavares, Maribel    
    Tran, Diane         
    Tsukamoto, Andrew   
    Wang, Mary          
    Young, Daniel       
    Wells, Steve        
    Wong, Justin        
    Johnson, Mary
    I get junk values for this too when i run it instead of sales.txt....
    Btw, for the names.txt, the number 16 at the top means there are 16 salespeople. they're listed one name per line (last name, first name).

    Please help!!
    Thank you

  2. #2
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    In the junk you get, you can see that the first thing you get is in common with the thing from .txt. Also the last one of the numbers is in common too.

    But from the last number you get on output the rest are junk!

    Why?
    Because you have an array, with every cell uninitialized. Which are the values of these cells? You don't know.. They contain junk
    You read your file.. EOF is reached. You stop reading, because there is no more data, but the array was bigger than your data, so which is the value of the uninitialized cells that were not filled with data? junk!

    I would initialize the array to a value that can not be contained at the file and when I was on print phase, I would stop when I would found that value.
    Or, because finding such a value can be difficult, I usually do this.
    Code - functions and small libraries I use


    Its 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " Harold Abelson

  3. #3
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334
    Your array is larger than your data. Try initializing the array
    Code:
    char array[25][20] = {0};
    Then when you print it out, only do so while the value is not zero.

  4. #4
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    But then if you get a zero in data, you are going to print less data than you get. I wouldn't recommend zero.
    Code - functions and small libraries I use


    Its 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " Harold Abelson

  5. #5
    Registered User
    Join Date
    Jan 2013
    Location
    San Jose, CA
    Posts
    53
    @std10093 and @Tclausex Thank you guys! I remember we learned to initialize the arrays, but somehow I totally left that out in my program! So i initialized it to 0, and now none of the junk values are printed. However, for the sales.txt, I want the results to be printed in 4 columns and 16 rows, just like in the sales.txt file. Somehow, i get this
    Code:
    425 20 25 2520 22 23
     2225 26 25 2230 28
    25 2625 30 45 2030 2
    5 20 2127 25 24 2620
     23 24 2028 26 24 25
    30 10 35 3228 29 30
    3515 16 15 1412 15 1
    2 1920 24 20 1810 15
    12 1632 30 33 29
    instead of this
    Code:
    4
    25 20 25 25
    20 22 23 22
    25 26 25 22
    30 28 25 26
    25 30 45 20
    30 25 20 21
    27 25 24 26
    20 23 24 20
    28 26 24 25
    30 10 35 32
    28 29 30 35
    15 16 15 14
    12 15 12 19
    20 24 20 18
    10 15 12 16
    32 30 33 29
    Does anyone know why?...
    Thanks so much again!

  6. #6
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334
    Quote Originally Posted by std10093 View Post
    But then if you get a zero in data, you are going to print less data than you get. I wouldn't recommend zero.
    That would certainly be true if he were converting the data to integers.

  7. #7
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334
    @Kal - you need to adjust your row/column indices when you encounter a newline in the file (since your array doesn't match your data in the file).

  8. #8
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    I didn't get what you said Tclausex. Also, mind to take a look at the code kal123456 posted. Also, prefer to post once at at a time.

    @kal123456 line 24 prevents the newline to be part of your array. I strongly suggest you to take the look at the link I provided in post #2. You use fgets and you are done
    Code - functions and small libraries I use


    Its 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " Harold Abelson

  9. #9
    Registered User
    Join Date
    Jan 2013
    Location
    San Jose, CA
    Posts
    53
    @std10093 in the link you provided, I'm a little confused with the code there haha...so, the program opens 2 files, right? the source file and target file?

    @Tclausex Ohh haha...wait but I don't get where to change them...in the for loops? and btw, you live in Saratoga, near me hahaha!

    also, the teacher won't let us use strings in our code!
    Last edited by kal123456; 01-29-2013 at 01:01 PM. Reason: forgot to mention that we can't use strings!

  10. #10
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Yes there are comments there. The code of course is not to be just copy pasted and you are done with your hw. This would not be fair. You can get ideas from there. Instead of writing to the target file, you should write in your array! Or better not. You don't need the data for further processing, so you could print something as soon as you read it to buf array.

    Take a try, but don't delete your previous code. It was a very good try
    Code - functions and small libraries I use


    Its 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " Harold Abelson

  11. #11
    Registered User
    Join Date
    Jan 2013
    Location
    San Jose, CA
    Posts
    53
    Ok, thanks everyone! I'll try to figure it out

  12. #12
    SAMARAS std10093's Avatar
    Join Date
    Jan 2011
    Location
    Nice, France
    Posts
    2,694
    Post back if needed
    Code - functions and small libraries I use


    Its 2014 and I still use printf() for debugging.


    "Programs must be written for people to read, and only incidentally for machines to execute. " Harold Abelson

  13. #13
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Your numbers are strictly formatted. Reading them in from the file with fscanf() would be normal.

    First, read in the first line, which tells you how many lines of data there are:
    fscanf(pf, "%d", &howMany)

    then a for loop to exploit that data:
    Code:
    for(i=0;i<howMany;i++) {
       fscanf(pf, "%d %d etc.
    }
    I wouldn't use putchar to print this out, btw. Use either string or an int, data type.

    Same basic idea with the names:

    read in the number of names - before the loop starts input for the rest of the names.

  14. #14
    Registered User
    Join Date
    Jan 2013
    Location
    San Jose, CA
    Posts
    53
    @Adak so i fixed up my code a little, and now it prints the table just like it is in the .txt file, but I STILL get the stupid junk values at the end!!! WHY?!

    Code:
    #include <stdio.h>
    
    int main()
    {
        int c, i, j, row, col, nl, cr;
    
        row = col = nl = cr = 0;
    
        FILE *fp = fopen("sales.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);
    
    
        // 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 the sales.txt file contains this:

    Code:
    4
    25 20 25 25
    20 22 23 22
    25 26 25 22
    30 28 25 26
    25 30 45 20
    30 25 20 21
    27 25 24 26
    20 23 24 20
    28 26 24 25
    30 10 35 32
    28 29 30 35
    15 16 15 14
    12 15 12 19
    20 24 20 18
    10 15 12 16
    32 30 33 29

  15. #15
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    The data is TELLING you, EXACTLY how many rows of data it has - you're just ignoring it, and blithely going ahead with getchar(), etc.

    Why?

    names are strings - not just chars. Digits are arranged in numbers, not chars.

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading values from text file
    By a.mlw.walker in forum C Programming
    Replies: 5
    Last Post: 01-14-2012, 05:02 PM
  2. Replies: 3
    Last Post: 10-21-2010, 12:39 PM
  3. reading in a text file containing hex values
    By gaza2k1 in forum C Programming
    Replies: 34
    Last Post: 02-29-2008, 06:15 PM
  4. Replies: 6
    Last Post: 11-11-2006, 01:10 PM
  5. Reading a file into a two dimensional array!!
    By Dilmerv in forum C++ Programming
    Replies: 6
    Last Post: 04-20-2006, 01:32 PM

Tags for this Thread


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