Reading from File and Storing into Array

This is a discussion on Reading from File and Storing into Array within the C Programming forums, part of the General Programming Boards category; Code: void function2 (void) { FILE *in; char var; int lab [MAX]; float test1, test2; int i = 0; if ...

  1. #1
    Registered User
    Join Date
    Oct 2011
    Posts
    23

    Reading from File and Storing into Array

    Code:
    void function2 (void)
    {
        FILE *in;
        char var;
        int lab [MAX];
        float test1, test2;
        int i = 0;
    
        if (( in =  fopen ("grades.txt", "r")) == NULL)
        {
            printf ("Error Opening File");
            return;
        }
        
     
        while ((fscanf(in, "%c", &var)) != EOF)
        {
        
            
            if (var == ':')
                fscanf (in, "&d", &lab[MAX]);
        }
        
        printf ("%d",&lab[1]);
    }

    The .txt file I opened has the following:
    Code:
    Lab  1: 10
    Lab  2: 18
    Lab  3: 22
    Lab  4: 19
    Lab  5: 14
    Lab  6: 16
    Lab  7: 18
    Lab  8: 18
    Exam 1: 65
    Exam 2: 42

    When I test, I should expect it to print "10" after printing the entire .txt to screen.

    It does not do this.

  2. #2
    C Newbie
    Join Date
    Oct 2011
    Posts
    59
    Quote Originally Posted by Magic staple View Post
    Code:
    printf ("%d",&lab[1]);
    When I test, I should expect it to print "10" after printing the entire .txt to screen.

    It does not do this.
    Try taking "&" out of this, so you will have...
    Code:
    printf ("%d",lab[1]);

  3. #3
    Registered User
    Join Date
    Oct 2011
    Posts
    23
    Hello, thanks for responding.

    I did as you suggested but the result is still not what I wanted.

    it printed "-858993460" but I wanted it to print "10".

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,258
    This is most certainly wrong because lab[MAX] does not exist:
    Code:
    fscanf (in, "&d", &lab[MAX]);
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    Oct 2011
    Posts
    23
    I set

    #define MAX 8


    I want to record the score of Lab 1 - 8.

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    lab[MAX] is the size of the array, but arrays are zero based in C. So the maximum index that can be valid is lab[MAX-1], not MAX.

    Also, you're currently scanning into the same array location, over and over again: lab[MAX], so it's just overwriting that same spot in memory. Give it a proper index,
    maybe
    Code:
    lab[i++];
    Something like that would do nicely.

  7. #7
    C Newbie
    Join Date
    Oct 2011
    Posts
    59
    Code:
    if (var == ':')
                fscanf (in, "&d", &lab[MAX]);
    Well this part here might be why. First off, I have no idea, since I must be less knowledgeable than you in C atm, what the first part is doing. But I am guessing that it is avoiding the rest of the line in the txt so it will only read the grade? For the second part though, you will need to have some kind of loop and counter for the array. EX: lab[k] with k increasing by one each loop, because right now it isn't storing any variables. By having lab[MAX] it is impossible to store any values. Let's say that MAX is 10, the array would therefore have 'slots' 0-9. Also, you need %d not &d.

    Here is an example of how to store values in an array if I wasn't being clear.
    Code:
    for(counter = 0; counter < MAX; counter++)
    {
    fscanf( in, "%d, lab[counter])
    }
    EDIT: Someone beat me to it. , I took too long when writing mine.

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,258
    Also, you should make sure that you do not attempt to store more than MAX elements in the array.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  9. #9
    Registered User
    Join Date
    Oct 2011
    Posts
    23
    Code:
    void function2 (void)
    {
        FILE *in;
        char var;
        int lab [MAX];
        int counter;
    
        if (( in =  fopen ("grades.txt", "r")) == NULL)
        {
            printf ("Error Opening File");
            return;
        }
        
     
        while ((fscanf(in, "%c", &var)) != EOF)
        {
        
            
            if (var == ':')
            {
        
                for(counter = 0; counter < MAX; counter++)
    {
    
        fscanf( in, "%d", lab[counter]);
    
        
        printf ("%d",lab[1]);
    }
        }
    }
    }
    That is what I am trying now but the program crash

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Magic staple View Post
    The .txt file I opened has the following:
    Code:
    Lab  1: 10
    Lab  2: 18
    Lab  3: 22
    Lab  4: 19
    Lab  5: 14
    Lab  6: 16
    Lab  7: 18
    Lab  8: 18
    Exam 1: 65
    Exam 2: 42
    Like this....
    Code:
    int lab[50];        // make lots of space
    char buffer[40]; // guarantee it holds one line
    int *idx;
    int i = 0;
    int j;
     
     while(fgets(buffer,39,in))  // read the line
       {
          idx = buffer;
         while (idx++ != ':');  // find the colon
         sscanf("%d",&lab[i]);  // get the number
         i++; 
       }
    
      for (j = 0; j < i; i++)
        printf("Lab %d = %d\n", j, lab[j]);

  11. #11
    Registered User
    Join Date
    Oct 2011
    Posts
    23
    Im sorry but I have trouble understanding your code.

    Code:
    #include <ctype.h>
    #define MAX 10
    
    
    void main (void);
    void function1 (void);
    void function2 (void);
    
    void main (void)
    {
        function1();
        function2 ();
    }
    
    
    void function1 (void)
    {
        FILE *in;
        char var;
        float lab [MAX];
        float test1, test2;
    
        if (( in =  fopen ("grades.txt", "r")) == NULL)
        {
            printf ("Error Opening File");
            return;
        }
        
     
        while ((fscanf(in, "%c", &var)) != EOF)
        {
        
            printf ("%c", var);
        }
    
        printf ("\n");
    
        fclose (in);
    }
    
    
    
    void function2 (void)
    {
        FILE *in;
        char var;
        int lab [MAX];
        int counter;
    
            int lab[50];        // make lots of space
    char buffer[40]; // guarantee it holds one line
    int * idx;
    int i = 0;
    int j;
      
    
    
    
        if (( in =  fopen ("grades.txt", "r")) == NULL)
        {
            printf ("Error Opening File");
            return;
        }
        
      
     while(fgets(buffer,39,in))  // read the line
       {
          idx = buffer;
         while (idx++ != ':');  // find the colon
         fscanf("%d",&lab[i]);  // get the number
         i++;
       }
     
      for (j = 0; j < i; i++)
        printf("Lab %d = %d\n", j, lab[j]);
    }
    (53): error C2369: 'lab' : redefinition; different subscripts
    (71): error C2440: '=' : cannot convert from 'char [40]' to 'int *'
    (72): error C2040: '!=' : 'int *' differs in levels of indirection from 'int'
    (73): error C2664: 'fscanf' : cannot convert parameter 1 from 'const char [3]' to 'FILE *'

  12. #12
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Two problems...
    1) you just did a copy paste of my code without noticing the double definitions of variables or anything else. In future treat examples as examples, not code you can just drop into your programs... most often they won't work, as you just discovered. At least, now you know why scoop and poop coding is such a terrible idea.

    2) I wrote that very quickly and didn't test it... so here's the fix.

    Code:
    #include <ctype.h>
    #include <stdio.h>
    
    #define MAX 20  // always make extra space
    
    void function1 (void);
    void function2 (void);
    
    int main (void)
    {
        function1();
        function2 ();
    
        return 0;
    }
    
    
    void function1 (void)
    {
        FILE *infile;
        char var;
        infile =  fopen ("grades.txt", "r");
        if (!infile)
          {
            printf ("Error Opening File");
            exit(0);
          }
     
        while (fscanf(in, "%c", &var) > 0)
           printf ("%c", var);
    
        printf ("\n");
        fclose (infile);
    }
    
    
    
    void function2 ( void )
    {
        FILE *infile;
        int lab [MAX];
        char buffer[40]; 
        char *idx;
        int i = 0;
        int j;
      
        infile =  fopen ("grades.txt", "r);
        if (! infile)
         {
            printf ("Error Opening File");
            exit(1);
        }
        
      
     while(fgets(buffer,39,infile))     
        {
           idx = buffer;
           while (*idx++ != ':');  // find the colon
           sscanf(idx, "%d", &lab[i[);  // get the number
         i++;
       }
     
      for (j = 0; j < i; i++)
        printf("Lab %d = %d\n", j, lab[j]);
    }
    Last edited by CommonTater; 12-04-2011 at 11:59 PM.

  13. #13
    Registered User
    Join Date
    Oct 2011
    Posts
    23
    sorry, there are still error that I do not know how to fix.

    (58): error c2446" '!=' : no conversion from 'int' to 'char *'
    (58): error c2040: '!=' : 'char *' differs in levels of indirection from 'int'

  14. #14
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Magic staple View Post
    sorry, there are still error that I do not know how to fix.

    (58): error c2446" '!=' : no conversion from 'int' to 'char *'
    (58): error c2040: '!=' : 'char *' differs in levels of indirection from 'int'
    You can't figure this out on your own?

    Time to read up on pointers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 12
    Last Post: 09-23-2010, 12:49 PM
  2. Help - Reading a file and storing it as a 2d Array.
    By MetallicaX in forum C Programming
    Replies: 2
    Last Post: 03-08-2009, 08:33 PM
  3. Reading all the numbes from a file and storing in an array
    By derek tims in forum C++ Programming
    Replies: 2
    Last Post: 04-02-2006, 04:01 PM
  4. Replies: 5
    Last Post: 10-02-2005, 01:15 AM
  5. 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