While loop problem

This is a discussion on While loop problem within the C Programming forums, part of the General Programming Boards category; Hi, I have a small problem with part of a program I have made. I want the user to select ...

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    8

    While loop problem

    Hi,

    I have a small problem with part of a program I have made. I want the user to select a number between 1 and 25 so I have used the following code (which I have abridged):
    <CODE>
    printf("\nPlease enter the number of records you would like to add (up to 25):\n");
    scanf("%d", &number);


    while(number <1 || number>25)
    {
    printf("\nPlease re-enter the number of records you would like to add:");
    scanf("%d", &number);
    }
    </CODE>

    The only problem is when a character is entered it goes into an infinite loop displaying the "Please re-enter...." sentence. Is this because of scanf? Is there a better function to use.

    Thanks in advance

  2. #2
    End Of Line Hammer's Avatar
    Join Date
    Apr 2002
    Posts
    6,231
    First off, code tags are with these brackets: [ ]
    Good try though

    Now the scanf() question comes up a lot. The better way to do it is with fgets() then atoi(), but if you want to stick with scanf(), check it's return code.

    You have asked it to get 1 number for you, so if it works, it will return 1. Check this in an if statement, if you don't get 1, ask the user to re-enter. Don't touch the number variable until scanf() returns 1.
    When all else fails, read the instructions.
    If you're posting code, use code tags: [code] /* insert code here */ [/code]

  3. #3
    Registered User
    Join Date
    Mar 2002
    Posts
    8
    Thanks Hammer!

    Works a treat.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Addition problem in loop
    By murjax in forum C Programming
    Replies: 3
    Last Post: 07-01-2009, 07:29 PM
  2. validation problem in a loop (newbie question)
    By Aisthesis in forum C++ Programming
    Replies: 11
    Last Post: 05-10-2009, 11:47 PM
  3. For Loop Problem
    By xp5 in forum C Programming
    Replies: 10
    Last Post: 09-05-2007, 05:37 PM
  4. Loop problem
    By Tesnik in forum C++ Programming
    Replies: 29
    Last Post: 08-23-2007, 11:24 AM
  5. A question related to strcmp
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 07-07-2007, 03:51 PM

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