Thread: Help with reading a string file into a 2d array

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    9

    Help with reading a string file into a 2d array

    cant get it to print an external file
    i have a file called months.dat
    with all the months in the file...

    Code:
    #include<stdio.h>
    #include<string.h>
    #define MAX_LEN 100
    
    int main(void)
    {
      int i;
      char filename[MAX_LEN];
      char words[12][MAX_LEN];
    
        printf("Give the file you want to open: ");
        scanf("%s",filename);
        FILE *inp=fopen("months.dat","r");  //open file for reading
         if(inp==NULL)
           printf("File does not exist");  //prints error message
         else
          {
    
              while(fscanf(inp,"%s",words[i])!=EOF)  //scan for a word
                 {  // i++; //increase letter by one
    
                     printf("%s",words[i-1]);
                     i++;
    
                 }
    
    
    
    
    
    
    
    }
    fclose(inp);
    return(0);
    }

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    I don't see where you are initializing your variable i to a value. It must be initialized before you can use it for the index variable for your array.

    Jim

  3. #3
    Registered User
    Join Date
    Sep 2011
    Posts
    9
    If. We're to initialize I=0; I still get random symbols when I run the program...I can't figure out why.

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    And if you initialize i to zero, which is probably correct, what happens the first time through this loop?
    Code:
              while(fscanf(inp,"%s",words[i])!=EOF)  //scan for a word
                 {  // i++; //increase letter by one
     
                     printf("%s",words[i-1]);
    Why i - 1?

    Jim

  5. #5
    Registered User
    Join Date
    Sep 2011
    Posts
    9
    Sorry the "//" befor I++ shouldn't be there. The words[i-1] was supposed to take away the \0 from the string to make it an array.
    I'm just rally confused about the whole concept of reading a string file into a 2d array.
    I figured by incrementing "I" I can scan though the whole file until I come to the end of it

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. TinyXML reading XML and storing to string array
    By airesore in forum C++ Programming
    Replies: 9
    Last Post: 10-27-2011, 11:57 AM
  2. Reading string from a file
    By kuma0177 in forum C Programming
    Replies: 1
    Last Post: 02-05-2010, 06:58 PM
  3. reading a string from a text file into a 2d array
    By duelord in forum C++ Programming
    Replies: 2
    Last Post: 11-22-2009, 07:29 AM
  4. Replies: 1
    Last Post: 04-25-2006, 12:14 AM
  5. reading file into a string array
    By lambs4 in forum C Programming
    Replies: 7
    Last Post: 01-22-2002, 04:23 PM