Thread: beginner ?

  1. #1
    Registered User
    Join Date
    Feb 2003

    Question beginner ?

    when i type anything but a number the program starts a endless loop. what code can i write into the program to stop this ,and what causes the loop.

    #include <stdio.h>
    int main()
       int x;
       printf("enter a numbr 1 thru 10\n");
       if (x<1 || x>10)
       printf("\nyou typed %d",x);
    Last edited by braincrash; 02-18-2003 at 12:14 AM.

  2. #2
    Registered User dharh's Avatar
    Join Date
    Jan 2002
    scanf doesn't catch the carriage return very well, so in your loop when it comes back around their is a carriage return in the buffer. This carriage return seem to remain in there and thus causes your infinite loop.

    This might work better for you:

    #include <stdio.h>
    int main() {
     int x = 0;
     char junk;
     while ( x < 1 || x > 10 ) {
       printf( "enter a numbr 1 thru 10\n" );
       scanf( "%d%c", &x, &junk );
     printf("\nyou typed %d",x);

  3. #3
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    First you'll need to check the return value of the scanf function to see if the user really entered a number:
    if(scanf("%d", %x) != 1)
       printf("This is not a number.\nPlease try again.\n");
    Then you'll need to get rid of the newline character, which is still in your input buffer:
    while(getchar() != '\n') /*do nothing */;
    Dharh, you example works on valid input but not if the user enters characters in stead of numbers. It's better to use the getchar function in a loop to remove the newline character.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Same old beginner question...
    By Sharmz in forum C Programming
    Replies: 15
    Last Post: 08-04-2008, 11:48 AM
  2. What are some good beginner programs I shouold make?
    By oobootsy1 in forum C# Programming
    Replies: 6
    Last Post: 08-09-2005, 02:02 PM
  3. Best Free Beginner Online Books/Tutorials?
    By Zeusbwr in forum C++ Programming
    Replies: 2
    Last Post: 10-12-2004, 05:52 PM
  4. Windows programming for beginner (Absolute beginner)
    By WDT in forum Windows Programming
    Replies: 4
    Last Post: 01-06-2004, 11:21 AM