c - Problems when using scanf with %i to capture date (mm dd yyyy) -
i'm writing program calculates number of elapsed days between 2 dates. this, have input dates integers in structure defined so:
struct date { int month; int day; int year; };
now, i've figured out how run program, it's bugging me user can't input date in (mm dd yyyy) format when month or day single digits. let me show code (please don't mind debug printf statements):
printf("enter start date (mm dd yyyy)\n"); scanf("%i %i %i", &startdate.month, &startdate.day, &startdate.year); // debug printf("start date = %i/%i/%i\n", startdate.month, startdate.day, startdate.year); // debug printf("start date month = %i", startdate.month); printf("enter end date (mm dd yyyy)\n"); scanf("%i %i %i", &enddate.month, &enddate.day, &enddate.year); // debug printf("end date = %i/%i/%i\n", enddate.month, enddate.day, enddate.year);
if user enters:
08 08 2004
then start date recorded as
0/8/0
which equal first 3 digits entered user. ok, understand that. understand user can enter "8 8 2004" , program runs fine...but believe programming details , 1 bugger. can me fix this?
using %i
conversion specifier causes scanf()
parse input if strtol()
called 0
base argument. so, since 08
begins 0
, , 8
not x
or x
, treats 08
octal sequence. but, since 8
not valid octal number, stops there, , result 0
first number.
the second number gets 8
, delimited whitespace. white space skipped, , third number parsing 08
octal again, resulting in 0
third number. remaining 8
, year 2004
not parsed.
use %d
parse decimal digits.
scanf("%d %d %d", &startdate.month, &startdate.day, &startdate.year);
as mentioned in comments, scanf()
should avoided. alternative, use fgets()
retrieve entire line of input first, , use sscanf()
parsing. allows better error recovery, since error can diagnosed line caused error, , line can gracefully skipped well. scanf()
meant structured input, , can give rough idea of scanning error occurred. and, errors cause input jam, leading confusing debugging sessions @ times.
Comments
Post a Comment