beginner ?

This is a discussion on beginner ? within the C Programming forums, part of the General Programming Boards category; when i type anything but a number the program starts a endless loop. what code can i write into the ...

  1. #1
    Registered User
    Join Date
    Feb 2003
    Posts
    5

    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.

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

  2. #2
    Registered User dharh's Avatar
    Join Date
    Jan 2002
    Posts
    51
    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:

    Code:
    #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);
    
     return(0);
    }

  3. #3
    Me want cookie! Monster's Avatar
    Join Date
    Dec 2001
    Posts
    680
    First you'll need to check the return value of the scanf function to see if the user really entered a number:
    Code:
    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:
    Code:
    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, 12:48 PM
  2. What are some good beginner programs I shouold make?
    By oobootsy1 in forum C# Programming
    Replies: 6
    Last Post: 08-09-2005, 03:02 PM
  3. Best Free Beginner Online Books/Tutorials?
    By Zeusbwr in forum C++ Programming
    Replies: 2
    Last Post: 10-12-2004, 06: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

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