Infinite loop

This is a discussion on Infinite loop within the C Programming forums, part of the General Programming Boards category; I stumbled upon a problem while I was coding. Code: void main() { int n; do { printf("Write a number ...

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    5

    Infinite loop

    I stumbled upon a problem while I was coding.

    Code:
    void main()
    {
    	int n;
    	do
    	{
    		printf("Write a number in interval [10,100]\n");
    		scanf("%d",&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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,452
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  3. #3
    Registered User
    Join Date
    Sep 2004
    Location
    California
    Posts
    3,246
    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, 03: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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21