Thread: why is this an infinite loop?

  1. #1
    Registered User
    Join Date
    Sep 2009
    Posts
    2

    why is this an infinite loop?

    here's the code it just keeps printing num and lcv but im not sure why.

    Code:
    #include<stdio.h>
    #define FILETOOPEN "ints"
    
    int main()
    {
      FILE *flptr;
      int lcv;
      int num;
      
      flptr = fopen(FILETOOPEN,"r");  
        
       while(lcv != EOF)
      {
        lcv = fscanf(flptr,"%d",&num);
        printf("\n  %d\n",num);
        printf("\n%d\n",lcv);       
      }
    }
    thanks in advance!

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    If your program cannot read a number, but is not at end-of-file (for instance, if your file has a letter in it somewhere, or some other non-numeric character), then you're just sunk. If you want to check for success, then check for success (whether lcv is 1).

  3. #3
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,268
    Because at some point fscanf() is returning 0 and not advancing the file pointer. Try something like this:
    Code:
       
    while(lcv != EOF)
    {    
        lcv = fscanf(flptr,"%d",&num);
        if(lcv == 0)
        {
            getc(flptr);
        }
        else
        {
            printf("\n  %d\n",num);
            printf("\n%d\n",lcv);       
        }
    }
    bit∙hub [bit-huhb] n. A source and destination for information.

  4. #4
    Registered User
    Join Date
    Sep 2009
    Posts
    2
    ok great thanks alot. I didnt realize the file pointer wouldnt advance if it "saw" a non-int

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 06-14-2009, 11:24 PM
  2. Cosine fucntion and infinite loop.
    By youareafever in forum C Programming
    Replies: 2
    Last Post: 11-07-2008, 04:45 AM
  3. Infinite Loop with GetAsyncKeyState
    By guitarist809 in forum Windows Programming
    Replies: 1
    Last Post: 04-18-2008, 12:09 PM
  4. Switch statement = infinite loop
    By Lucid003 in forum C++ Programming
    Replies: 10
    Last Post: 10-10-2005, 12:46 AM
  5. stays in loop, but it's not an infinite loop (C++)
    By Berticus in forum C++ Programming
    Replies: 8
    Last Post: 07-19-2005, 11:17 AM