Thread: Infinite loop

  1. #1
    Registered User
    Join Date
    May 2009

    Infinite loop

    I stumbled upon a problem while I was coding.

    void main()
    	int n;
    		printf("Write a number in interval [10,100]\n");
    	}while(n<10 || n>100);
    This works just fine when I enter a number, but when I enter a char for example "A", it just starts repeating "Write a number in interval [10,100]\n" infinitely. I tried to explain this to myself but I just couldn't come to a logical conclusion.

    In my opinion n should be initialized with 65 and program should leave the loop and end.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    A isn't a number.
    The next time around the loop, A still isn't a number.
    The next time around the loop, A still isn't a number.
    The next time around the loop, A still isn't a number.

    Unless you do something to fix that, you're going nowhere.

    Try using fgets() to read a whole line, then using say sscanf to parse it.
    See the FAQ.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2004
    When you enter "A", scanf fails and n is not assigned any value. That is why the loop goes forever. Check the return value of scanf() to see if 'n' was successfully given a value.
    bit∙hub [bit-huhb] n. A source and destination for information.

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