Error Checking

This is a discussion on Error Checking within the C Programming forums, part of the General Programming Boards category; Code: printf("1. Britain\n"); printf("2. Denmark\n"); printf("3. Japan\n"); printf("4. USA\n"); printf("5. Exit Program\n\n"); /* Ask user for there choice */ /* ...

  1. #1
    Registered User
    Join Date
    Nov 2003
    Posts
    4

    Error Checking

    Code:
    printf("1. Britain\n");
       	printf("2. Denmark\n");
       	printf("3. Japan\n");
       	printf("4. USA\n");
       	printf("5. Exit Program\n\n");
    
       	/* Ask user for there choice */
       	/* And Asign the choice to varabial manu_choice, which is of int data type */
    
    
    
    do
    {
       	printf("Please Enter Your Country Selection From The Menu: \t");
       	error = scanf("%d",&menu_choice);
          fflush(stdin);
    } while ( menu_choice < 1 || menu_choice > 5 && error == 0);






    Is this enough to stop any values being entered at the inital menue choice? i only want 1 - 5 to be accepted and anything else should prompt the user again.

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,485
    > fflush(stdin);
    This isn't defined - if it works at all, it's a compiler specific thing
    See the FAQ

    Best bet is
    Code:
    char buff[BUFSIZ];
    if ( fgets( buff, sizeof buff, stdin ) != NULL ) {
        error = sscanf( buff, "%d", &menu_choice );
    } else {
        /* exit while() loop - its EOF - no more input is possible */
        break;
    }
    > while ( menu_choice < 1 || menu_choice > 5 && error == 0);
    Close!
    But you should choose a better order.
    If error is 0, then menu_choice is undefined (you didn't read anything into it)

    while ( error == 0 || menu_choice < 1 || menu_choice > 5 );
    Only tests menu_choice if error is not zero (that is, error is 1 and menu_choice has a valid value).
    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
    Someone give me a job DigitalKhaos's Avatar
    Join Date
    Apr 2003
    Posts
    4
    Why not just use a switch(menu_choice)?

Popular pages Recent additions subscribe to a feed

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