scanf ?

This is a discussion on scanf ? within the C Programming forums, part of the General Programming Boards category; How do I catch bad input in scanf()? For example, if scanf is expecting integer but the user types in ...

  1. #1
    Registered User
    Join Date
    Jan 2002
    Posts
    5

    scanf ?

    How do I catch bad input in scanf()? For example, if scanf is expecting integer but the user types in alpha, the program continues with last good integer input. In C++ I used a combo of cin.good, cin.clear and cin.ignore. The while (getchar() != '\n'); works for clearing out stream but how do i test for input data not matching expected data type?

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    I dont think that you can with scanf() although if I'm wrong salem will correct me but I believe a better strategy would be to use fgets() and get all input as a string and then validate the string using isalpha(),or isdigit() etc. then if you need an int or a double you can pass the validated string to atoi() or atof(). You could also use sscanf() on the buffer filled by fgets() but i guess it just boils down to not using scanf().
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,659
    Like Stoned_Coder said

    scanf returns a lot of potential status results which you have to consider, and take action on each one.

    The fgets() approach has the following advantages
    1. it separates the EOF test from the conversion results, so your test of the success of sscanf() only has to worry about success/fail of the conversion.
    2. if you don't like the buffer, fgets() will have already read upto the next \n, so the input stream is always tidy. You just re-use the buffer in the next fgets() call.
    3. you can have several attempts at deciding what a buffer means, should it be necessary (eg. enter a number, or 'q' to quit).
    4. when it comes to reading in strings using %s, it becomes more tricky to prevent accidental buffer overflow possibilities.

    Some code
    Code:
    #include <stdio.h>
    
    void use_scanf ( ) {
        int i, res;
        printf( "Enter number\n" );
        res = scanf( "%d", &i );
        if ( res == 1 ) {
            // success
            printf( "Congrats, you entered %d\n", i );
        } else
        if ( res == 0 ) {
            // failed, purge input
            // this should also check for EOF
            printf( "Junking bad input\n" );
            while ( getchar() != '\n' );
        } else {
            // EOF to start with
            printf( "Found EOF\n" );
        }
    }
    void use_fgets ( ) {
        char buff[BUFSIZ];
        int i, res;
        printf( "Enter number\n" );
        if ( fgets( buff, BUFSIZ, stdin ) != NULL ) {
            res = sscanf( buff, "%d", &i );
            if ( res == 1 ) {
                // success
                printf( "Congrats, you entered %d\n", i );
            } else {
                // failed, just ignore the buffer
                printf( "Ignoring bad input\n" );
            }
        } else {
            // EOF to start with
            printf( "Found EOF\n" );
        }
    }
    
    int main() {
        // choose one
    //    use_scanf();
        use_fgets();
        return 0;
    }

  4. #4
    Banned Troll_King's Avatar
    Join Date
    Oct 2001
    Posts
    1,784
    Code:
    While ( scanf("%d",&num) != 1 || num > 32000 || num < 0)
    {
       printf("Try again: ");
       while( getchar() != '\n') continue;
    }
    Works something like that. You can set the range as long as it is in the rage of the built in type.

  5. #5
    Registered User
    Join Date
    Jan 2002
    Posts
    5
    Thanks again! this board is great!...your time is greatly appreciated.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. scanf() consideres useless
    By Snafuist in forum C Programming
    Replies: 15
    Last Post: 02-18-2009, 07:35 AM
  2. Help with a basic scanf procedure.
    By killpoppop in forum C Programming
    Replies: 9
    Last Post: 11-03-2008, 03:39 PM
  3. Replies: 2
    Last Post: 02-20-2005, 12:48 PM
  4. Scanf and integer...
    By penny in forum C Programming
    Replies: 3
    Last Post: 04-24-2003, 06:36 AM
  5. scanf - data is "put back" - screws up next scanf
    By voltson in forum C Programming
    Replies: 10
    Last Post: 10-14-2002, 04:34 AM

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