Thread: while loop trouble

  1. #1
    Musicman - Canora
    Join Date
    Aug 2005
    Location
    Melbourne
    Posts
    252

    while loop trouble

    Hey guys im trying to read in a file and list numbers to each line in the file but for some reason im getting a runtime logical error inside my while loop.






    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char **argv)
    {
    
        int line_no = 0;
        int input_char = 0;
        int nl = 1;
        FILE *fp;
    
        if(argc !=2) /* check for 2 arguments*/
        {
    
          fprintf(stderr, "invalid usage :%s\n", argv[0]);
          return 1; /* stop processing if failes */
    
        }
    
        if((fp = fopen(argv[1], "r")) == NULL) 
        /* opens file for reading and checks if it exists */
        {
         
         fprintf(stderr, "invalid usage: %s\n", argv[0]);
         return 1; /* stop processing if fails*/
    
        }
    
    
          while(input_char !=EOF)
     
              /* keep asking for input while not end of file*/
          {
              if ( nl )
              {
                 printf("\n%d ", line_no);
                 line_no++;
    	  }
    	  else
              { 
    	     putc(input_char, stdout);
    	     input_char = getc(fp);   
    	     nl = input_char == '\n';
              }
        }
           
        
    
        fclose(fp);
    
    
    
        return EXIT_SUCCESS;
    
    }

  2. #2
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    You are starting off with nl equal to 1, then in the while loop, you are checking if nl is true (non-zero). Since it is, it simply prints line_no then increases line_no. nl is not set to zero, so the while loop goes back again, nl is still 1.. so this goes on forever.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Rewriting a for loop as a while/do-while loop
    By Ashfury in forum C++ Programming
    Replies: 7
    Last Post: 04-27-2007, 02:20 PM
  2. loop the loop - feeling foolish
    By estos in forum C Programming
    Replies: 2
    Last Post: 04-07-2007, 02:45 AM
  3. loop needed also how to make input use letters
    By LoRdHSV1991 in forum C Programming
    Replies: 3
    Last Post: 01-13-2006, 05:39 AM
  4. trouble with a for loop with an if statement nested in
    By phoenix-47 in forum C++ Programming
    Replies: 4
    Last Post: 12-14-2005, 04:24 PM
  5. I need help as soon as possible.
    By hyrule in forum C++ Programming
    Replies: 7
    Last Post: 11-09-2005, 05:49 PM