Reading an array of strings from a text file?

This is a discussion on Reading an array of strings from a text file? within the C Programming forums, part of the General Programming Boards category; So I have a text file which contains information like the following: 3800 Victor Lee; 2.8 This is a student ...

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    46

    Reading an array of strings from a text file?

    So I have a text file which contains information like the following:

    3800 Victor Lee; 2.8

    This is a student ID, name, and gpa.
    The file begins with an integer indicating how many students are listed in the text file.
    I have already scanned in the integer value from the text file and used it to initialize a size variable.

    My problem is that I must scan each line student information into an array of strings and I can't seem to figure it out.

    Ideally it would resemble:
    temp[0] = "first line of information from file";
    temp[1] = "second line"
    and so on.

    I have tried several variations of a while loop using fgets but no results have turned up.

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    There are a few ways to do this, of course. If you have been taught structs yet, I would say use one array of structs for this, but your question leads me to believe you haven't learned about them, just yet.
    Call this #1.

    #2:
    Another way to do this would be to use "parallel arrays". A char array for the string name, an int array, and a float array. These would work like so:

    Id[0] is 3800 names[0] is Victor Lee gpa[0] is 2.8

    With the index of 0 being the uniting factor that glues everything together.

    #3:
    Still another way to do this, is to have one char array, and put everything into the array, making numbers change into just char digits that look like numbers: 2.8 would be 2.8, but it would just be text now. Making averages of the students gpa's, for instance, would be a bit of a pain now.

    I think you're leaning toward # two or three, but I'm not sure which.

    Using fgets() is the right way to go for #3, clearly:
    Code:
    int i = 0;
    while((fgets(charArrayName[i++], sizeof(charArrayName), filePointerName)) != NULL) {
        all your processing code in here 
    }
    Last edited by Adak; 11-12-2011 at 09:54 PM.

  3. #3
    Registered User
    Join Date
    Nov 2011
    Posts
    46
    This is what I ended up doing:

    while(!feof(fp1))
    (fgets(temp, MAX_SIZE, fp1));

    I need not worry so much about the gpa and student id because the next step is to copy only the names into an
    array of strings in the format : last name, first name
    so the rest of the information will be discarded anyway

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    OK. Check your feof(). It can result in the last entry being repeated unexpectedly, because feof() doesn't work as you might expect.

  5. #5
    Registered User
    Join Date
    Nov 2011
    Posts
    46
    You're right, the last entry was repeated. When copying over the names to an array of strings, I have a size variable which is the max number of entries
    Does it make that much of a difference if when creating the loop to do so that I leave the first array as is?
    Or would you recommend getting rid of the repeated last entry?

  6. #6
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Dump the !feof(), and use the while loop I posted. Problem solved. Don't deal with bad input, if at all possible. Nip it in the bud!

  7. #7
    Registered User
    Join Date
    Nov 2011
    Posts
    46
    I tried your loop:
    Code:
    int i = 0;
          while((fgets(temp[i++], sizeof(temp), fp1)) != NULL)
          {
                fputs(temp, stdout);
          }
    I used fputs to verify that it had been read in correctly but nothing was printed to the screen. Any ideas?

  8. #8
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Lots of idea's, (tons of 'em), but I need to see the rest of your code to see what's going on. Is temp a 2D array, is it sized large enough to include the end of string char, why are you printing only the base row, is fp1 valid -- did you check that the file was actually opened?

    Well silly me. The a[i] is what the sizeof(a[i]) should refer to, not just sizeof(a). This was for a 2D array, right? (It's late).
    Last edited by Adak; 11-13-2011 at 02:51 AM.

  9. #9
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    With this in a text file named "Edelweiss.txt", you can see how this works with this example:

    Code:
    #include <stdio.h>
    
    int main(void) {
       int i;
       char a[7][128];
       FILE *fp=fopen("Edelweiss.txt", "r");
       if(!fp) {printf("\nError: unable to open the file.\n"); return 1;}
    
       i=0;
       while((fgets(a[i],sizeof(a[i]), fp)) != NULL) {
          fputs(a[i++],stdout);
          getchar();
       }
       fclose(fp);
    
       return 0;
    }
    Edelweiss.txt should have:

    "Edelweiss, edelweiss, every morning you greet me.\n\
    Small and white, clean and bright, you look happy to meet me.\n\
    Blossom of snow may you bloom and grow, bloom and grow forever.\n\
    Edelweiss, edelweiss, bless my homeland forever.\n\
    Small and white, clean and bright, you look happy to meet me\n\
    Blossom of snow, may you bloom and grow, bloom and grow forever.\n\
    Edelweiss, edelweiss, bless my homeland forever."

  10. #10
    Registered User
    Join Date
    Nov 2011
    Posts
    46
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <crtdbg.h> 
    #include <string.h>
    #define MEM_ERROR printf("Error, could not access file!\n")
    #define MAX_SIZE 1000
    #define FLUSH while(getchar() != '\n')
    
    int getSize (void);
    char** buildList (int);
    
        FILE* fp1;
    
    int main (void)
    {
        int size;
        char** list;
    
       size = getSize();
       printf("%d is the size\n", size);
       list = buildList(size);
       
       free(list);
    
        printf( _CrtDumpMemoryLeaks() ? "\nMemory Leak\n" : "\nCongratulatons! No Memory Leak\n"); 
    
        system("pause");
    
       return 0;
    
    }
    
    int getSize (void)
    {
        int size;
    
        if(!(fp1 = fopen("gpa.txt", "r")))
            MEM_ERROR;
    
        fscanf(fp1, "%d", &size);
    
        return size;
    }
    
    char** buildList (int size)
    {
        char** list;
        char temp[MAX_SIZE];
        char* pFirst;
        char* pLast;
        int i;
    
        if(!(list = (char**)calloc (size + 1, sizeof(char*))))
                MEM_ERROR;
    
    /*   
     while(!feof(fp1))
        {
             (fgets(temp, MAX_SIZE, fp1));
             fputs(temp, stdout);
    
          }
          */
          i = 0;
          while((fgets(&temp[i], sizeof(temp[i]), fp1)) != NULL)
          {
                fputs(&temp[i++], stdout);
                getchar();
          }
    
        fclose(fp1);
        
        return list;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading Strings from a text file?
    By Soxcrates in forum C++ Programming
    Replies: 7
    Last Post: 10-31-2010, 06:53 PM
  2. Reading Multiple Multi-Part Strings From a Text File
    By bengreenwood in forum C++ Programming
    Replies: 2
    Last Post: 06-02-2009, 10:43 AM
  3. Problem reading file into array of strings
    By myrddinb in forum C Programming
    Replies: 7
    Last Post: 03-25-2005, 11:12 PM
  4. Putting strings into an array from a text file.
    By JLan in forum C Programming
    Replies: 5
    Last Post: 11-20-2003, 06:34 PM
  5. Reading strings from a file and storing into an array
    By Rizage in forum C++ Programming
    Replies: 1
    Last Post: 10-24-2002, 03:04 AM

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