Thread: What is a good alternative for scanf?

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    13

    What is a good alternative for scanf?

    So I have this for my main function.
    Code:
    int main(void)
    {
    int year;
    int month;
    int first_day;
    
    do{
    printf("Enter a month (1 - 12): ");
    scanf("%d", &month);
    } while (month < 1 || month > 12);
    
    do{
    printf("Enter a year (1978 - 3000): ");
    scanf("%d", &year);
    } while (year < 1978 || year > 3000);
    
    first_day = first_day_year(year);
    leapyear(year);
    calendar(month, year, first_day);
    
    printf("\n");
    
    return 0; 
    }
    How can I revise the part where the program asks for a number from 1-12 (for the months) and 1978-3000 (for the year) without it going through an infinite loop when the user enters letters (a-z, A-Z) and other characters? It should only accept the specified numbers.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    It would be a good idea to check the return value from scanf() - as that allows you to detect any circumstances where values have not actually been read. If scanf() returns zero (or EOF) it has failed to read anything, and looping will occur unless you write code to recover from that.

    Alternatively, use fgets() to read a line of input (as an array of car). Parse the line any way you like.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,562
    Use fgets() and strtol() / strtoul() / strtod() if you really want to make it bomb-proof.

    scanf functions do not detect numeric overflow (for example).
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. What is the alternative to malloc?
    By huwan in forum C Programming
    Replies: 11
    Last Post: 03-24-2011, 07:08 AM
  2. Any alternative?
    By sCandal2 in forum Windows Programming
    Replies: 4
    Last Post: 01-11-2006, 04:30 PM
  3. gets() alternative
    By Mastadex in forum C Programming
    Replies: 5
    Last Post: 12-12-2004, 12:28 AM
  4. alternative to cin
    By Unregistered in forum C++ Programming
    Replies: 18
    Last Post: 06-25-2002, 05:14 PM