Thread: Reading in text file to an array?

  1. #1
    Registered User
    Join Date
    Feb 2012
    Posts
    19

    Reading in text file to an array?

    I am given a poem in a text file, and I have to

    1. store all lines in a character matrix

    2. Find the number of characters in the longest line

    3. Write the lines to a new text file, but add the line number for every 5th line, aligned on the right hand side.

    It should look something like this:

    This is a poem
    Poem Poem Poem Poem
    Poem Poem Poem Poem
    Poem Poem Poem Poem
    Poem Poem Poem Poem 5
    ....


    I am completely lost, this is what I have so far.

    Code:
    FILE *fp;
        char *StrArr[100];
    
    
    
    
        fp = fopen("myFile.txt", "r");
        int i;
        for( i=0; i<100; i++)
        {
            fscanf(fp, "%s\n",&StrArr[i]);
            printf("%s",&StrArr[i] );
        }
    This doesn't even print the lines right, can anyone please help me?

    Thanks a lot!

  2. #2
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    You don't need to use pointers in the fscanf() or the printf().

    Also, I may be wrong, but the "\n" isn't necessary in the format string of the fscanf().

  3. #3
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Try this to input your poem with. Note the space before the %. Without that space, you may get only one line of the poem.

    Code:
       while((fscanf(fp, " %[^\n]s",StrArr[i])) > 0) {
          printf("%s",StrArr[i++]);
          //getchar();    //just for debug help, if needed
       }
    When taking in a whole line of text, I generally prefer the fgets() function, because it's more robust than the scanf() family of functions.

  4. #4
    Registered User
    Join Date
    Feb 2012
    Posts
    19
    Quote Originally Posted by Adak View Post
    Try this to input your poem with. Note the space before the %. Without that space, you may get only one line of the poem.

    Code:
       while((fscanf(fp, " %[^\n]s",StrArr[i])) > 0) {
          printf("%s",StrArr[i++]);
          //getchar();    //just for debug help, if needed
       }
    When taking in a whole line of text, I generally prefer the fgets() function, because it's more robust than the scanf() family of functions.




    Ok, now I have this.

    Code:
    char StrArr[1000];
    
    
    
    
        fp = fopen("myFile.txt", "r");
        int i;
        for( i=0; i<1000; i++)
        {
            while((fscanf(fp, " %[^\n]s",StrArr[i])) > 0) {
            printf("%s",StrArr[i++]);
            getchar();
            }
        }
        fclose(fp);

    Its not printing anything out now, any suggestions whats wrong?

  5. #5
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by Le23ron View Post
    Ok, now I have this.
    Code:
    //char StrArr[1000];
    char StrArr[100][100];
    
    
    
    
        fp = fopen("myFile.txt", "r");
        int i;
    
    //you haven't checked if the file has been opened or not.
    if(!fp) {
       printf("Error: file did not open!\n");
       return 1;
    }
    //    for( i=0; i<1000; i++)
    //   {
            while((fscanf(fp, " %[^\n]s",StrArr[i])) > 0) {
            printf("%s",StrArr[i++]);
            //getchar();
          }
        //}
        fclose(fp);
    Try that. If it doesn't work, you'll have to post the poem. The above was tested on a song lyric, and works fine.

    It won't works fine for any blank lines, however. Does your poem have blank lines in it? The blank lines will be "skipped", as the program is now.
    Last edited by Adak; 02-12-2012 at 04:35 PM.

  6. #6
    Registered User
    Join Date
    Feb 2012
    Posts
    19
    Quote Originally Posted by Adak View Post
    Code:
    //char StrArr[1000];
    char StrArr[100][100];
    
    
    
    
        fp = fopen("myFile.txt", "r");
        int i;
    
    //you haven't checked if the file has been opened or not.
    if(!fp) {
       printf("Error: file did not open!\n");
       return 1;
    }
    //    for( i=0; i<1000; i++)
    //   {
            while((fscanf(fp, " %[^\n]s",StrArr[i])) > 0) {
            printf("%s",StrArr[i++]);
            //getchar();
          }
        //}
        fclose(fp);
    Try that. If it doesn't work, you'll have to post the poem. The above was tested on a song lyric, and works fine.

    It won't works fine for any blank lines, however. Does your poem have blank lines in it? The blank lines will be "skipped", as the program is now.

    Ok, it keeps printing out the file will not open every time. I have a poem saved on my desktop called myFile.txt with this poem in it, still not sure whats wrong.

    Either to die the death or to abjure
    For ever the society of men.
    Therefore, fair Hermia, question your desires;
    Know of your youth, examine well your blood,
    Whether, if you yield not to your father's choice,
    You can endure the livery of a nun,
    For aye to be in shady cloister mew'd,
    To live a barren sister all your life,
    Chanting faint hymns to the cold fruitless moon.


    I can't get the program to read it in at all.

  7. #7
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Just find your program file - the compiled exe program.

    Put your poem file into the same folder as the exe program. Remove any reference you might have to any other folder, inside your program, and then run it.

    I don't see anything amiss in your poem contents, to cause a problem.

  8. #8
    Registered User
    Join Date
    Feb 2012
    Posts
    19
    Quote Originally Posted by Adak View Post
    Just find your program file - the compiled exe program.

    Put your poem file into the same folder as the exe program. Remove any reference you might have to any other folder, inside your program, and then run it.

    I don't see anything amiss in your poem contents, to cause a problem.


    Ok, I'm using codeblocks, I tried putting the text document on my desktop, in with the project and c-source file, the exe file, everything and I still cant read the poem in

  9. #9
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Maybe you're spelling it wrong? Don't forget that C is case-sensitive.
    Devoted my life to programming...

  10. #10
    Registered User
    Join Date
    Feb 2012
    Posts
    19
    Great, I got everything working. All I need is to find how many characters the longest line has and print it. I tried to set up some sort of counter, this is what I have, but am not sure where to go from here.
    Code:
    int count=0;//count characters of longest line
        while((fscanf(fp, " %[^\n]s",StrArr[i])) > 0)
        {
            printf("%s",StrArr[i++]);
            count++;
        }

  11. #11
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    That's easy. "If (count > max) max = count;"

    EDIT: If count was the characters on each line...
    Last edited by GReaper; 02-12-2012 at 10:18 PM.
    Devoted my life to programming...

  12. #12
    Registered User
    Join Date
    Jan 2009
    Posts
    1,485
    Quote Originally Posted by Le23ron View Post
    Great, I got everything working. All I need is to find how many characters the longest line has and print it. I tried to set up some sort of counter, this is what I have, but am not sure where to go from here.
    Code:
    int count=0;//count characters of longest line
        while((fscanf(fp, " %[^\n]s",StrArr[i])) > 0)
        {
            printf("%s",StrArr[i++]);
            count++;
        }
    Count in you example would contain the amount of printed lines. To get the length, the simplest is to use strlen(). Although, you can not overwrite this value for each line, first you need to compare if it's greater than the previous largest value.

  13. #13
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Imagine, that I gave you a bushel of apples, and requested you pick out the biggest one. How would you do that?

    Maybe:

    1) Look at the first apple you took out of the bushel basket
    2) compare all the other apples, one at a time, to see if they're bigger.
    3) If you found a bigger apple, that would become the new biggest apple that the others in the basket, would be compared to

    Programming works the same way:
    Code:
     int longest;
                i=0;
                while((fscanf(fp, " %[^\n]s",StrArr[i])) > 0)
                {
                   length = strlen(StrArr[i]);
                   if(i == 0)
                      longest = i;
                   else {
                      if(length > StrArr[longest]) {
                         longest = i;
                      }
                   } //end of else
                   printf("%s",StrArr[i++]);
                    
                } //end of while
              
                printf("Longest line was %s, with length of %d\n",StrArr[longest], strlen(StrArr[longest]);
    If you want to count the actual letters (as opposed to the letters and the spaces, as I have here, then you need to use a while or for loop, and "walk" down the row of StrArr[longest], counting as you go.

  14. #14
    Registered User
    Join Date
    Feb 2012
    Posts
    19
    Great, that was very informative and helpful, thanks a lot!

  15. #15
    Registered User
    Join Date
    Feb 2012
    Posts
    19
    Finally, how would I write my poem back out to a new text file once I was done?

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reading an array of strings from a text file?
    By jeanermand in forum C Programming
    Replies: 9
    Last Post: 11-14-2011, 09:41 PM
  2. trouble reading a text file into an array
    By Ciaran in forum C Programming
    Replies: 15
    Last Post: 04-04-2011, 05:14 PM
  3. reading from a text file into an array and coding.
    By tombocollbo in forum C Programming
    Replies: 6
    Last Post: 12-09-2010, 01:25 PM
  4. 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
  5. Reading in an array of text from a file?
    By suzakugaiden in forum C++ Programming
    Replies: 6
    Last Post: 01-04-2006, 03:17 PM