Thread: Help displaying line numbers of a text document

  1. #1
    Registered User
    Join Date
    May 2006
    Posts
    8

    Help displaying line numbers of a text document

    Sorry for being such a noob before and asking for help without trying prior to posting. In any case I've figured out most of my program, I'm just having trouble getting my program to display the line numbers before to the lines of text. This is what I have so far:

    Code:
    #include <stdio.h>
    #define LINE_LENGTH 80
    
    int main()
    {
        FILE *fp = fopen("test.txt", "r");
        char line[LINE_LENGTH];
        while (fgets(line, LINE_LENGTH, fp) != NULL) 
        {
              printf( "%s", line);
        }
        getchar();
    }

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Code:
       int count = 0;
       while ( fgets(line, sizeof line, fp) != NULL )
       {
          printf( "%2d : %s", ++count, line);
       }
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    May 2006
    Posts
    8
    Thanks a bunch, can you explain to me what %2d is?

  4. #4
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    It means that the integer will be at least two characters in size, and will be padded with spaces if it's less than two chars. That is, printf("%2d", 3) prints "<space>3". You can make printf pad with zeros instead of spaces with printf("%02d", 3) which prints "03".
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  5. #5
    Registered User
    Join Date
    May 2006
    Posts
    8
    I see thank you very much

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. reading from text file
    By jamez in forum C Programming
    Replies: 3
    Last Post: 11-30-2005, 07:13 PM
  2. Replies: 1
    Last Post: 07-13-2002, 05:45 PM
  3. Ok, Structs, I need help I am not familiar with them
    By incognito in forum C++ Programming
    Replies: 7
    Last Post: 06-29-2002, 09:45 PM
  4. inputting line of text vs. integers in STACK
    By sballew in forum C Programming
    Replies: 17
    Last Post: 11-27-2001, 11:23 PM
  5. text line termination
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 09-09-2001, 04:39 AM