Help with scanf

Discussion in 'C Programming' started by Sivarn, Apr 1, 2004.

  1. Sivarn

    Sivarn Guest

    I'm writing a program for that takes dates as input using scanf. I
    want to verify that the user is inputting a full 4 digits for the
    year. How do I do this? I know that the return value on printf is the
    number of printed characters; so if I could somehow get my year
    variable to store the leading zeros, I could just run a check:

    int dummy = 0;

    dummy = printf("%d", year);

    if (dummy != 4)
    {
    ...do something...
    }
     
    Sivarn, Apr 1, 2004
    #1
    1. Advertising

  2. >I'm writing a program for that takes dates as input using scanf. I
    >want to verify that the user is inputting a full 4 digits for the
    >year.


    Why?

    >How do I do this?


    Use the %s format and handle the year as a string. At this point
    you can verify that strlen() of the string is 4. At the same time
    you could check that all 4 characters are digits. strtol() or
    atoi() can convert the value to an integer after you've checked the
    length, or you could use sscanf() on it.

    >I know that the return value on printf is the
    >number of printed characters; so if I could somehow get my year
    >variable to store the leading zeros, I could just run a check:


    Integers don't store leading zeros.
    Strings do.

    Depending on what you are inputting, you could also range check the
    year (e.g. a birth year of someone living now is unlikely to be
    less than 1000).

    Gordon L. Burditt
     
    Gordon Burditt, Apr 1, 2004
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ramprasad A Padmanabhan

    scanf help again

    Ramprasad A Padmanabhan, Jul 24, 2003, in forum: C Programming
    Replies:
    3
    Views:
    448
    Dave Thompson
    Aug 8, 2003
  2. Rob

    help with infinite loops and scanf

    Rob, Jul 26, 2003, in forum: C Programming
    Replies:
    8
    Views:
    805
    Peter Shaggy Haywood
    Jul 29, 2003
  3. Sivarn

    Help with scanf

    Sivarn, Apr 1, 2004, in forum: C Programming
    Replies:
    23
    Views:
    1,316
    Dan Pop
    Apr 13, 2004
  4. =?ISO-8859-1?Q?Martin_J=F8rgensen?=

    scanf (yes/no) - doesn't work + deprecation errors scanf, fopen etc.

    =?ISO-8859-1?Q?Martin_J=F8rgensen?=, Feb 16, 2006, in forum: C Programming
    Replies:
    185
    Views:
    3,524
    those who know me have no need of my name
    Apr 3, 2006
  5. =?ISO-8859-1?Q?Martin_J=F8rgensen?=

    difference between scanf("%i") and scanf("%d") ??? perhaps bug inVS2005?

    =?ISO-8859-1?Q?Martin_J=F8rgensen?=, Apr 26, 2006, in forum: C Programming
    Replies:
    18
    Views:
    709
    Richard Bos
    May 2, 2006
Loading...

Share This Page