I am scanning for a date in the format mm-dd-yyyy and I need to take out three ints and use them for multiple things. How can I create three integers with mm dd and yyyy? Thanks!
Asked
Active
Viewed 61 times
0
-
1Possible duplicate of [reading a date with sscanf](http://stackoverflow.com/questions/12071342/reading-a-date-with-sscanf) – mrks Apr 30 '17 at 17:29
2 Answers
1
Use the sscanf
call from <stdio.h>
.
char line[80];
int m, d, y;
fgets(fgets(line, sizeof line, stdin);
sscanf(line, "%d-%d-%d", &m, &d, &y);
It is better to use fgets+sscanf instead of scanf directly, because scanf has the notorious \n
issue and does not check buffer lengths.

lost_in_the_source
- 10,998
- 9
- 46
- 75
-
-
its returning numbers much larger than it should, and not allowing me to input... it's returning m = 3952640 d = 0 y = 4200896 (This is before it is even allowing me to enter a date. Nothing changes when I input a date) – T. Daniels Apr 30 '17 at 18:41
-
@xing this is my code int main() { int x; printf("\n\t\t\t1) Input date (mm/dd/yyyy) to find days passed"); printf("\n\t\t\t2) Input passed days to find date in the year"); printf("\n\n\t\t\tYour choice (1/2): "); scanf("%d", &x); if(x == 1) { char line[80]; int m, d, y; printf("Please input date (mm-dd-yyyy): "); fgets(stdin, sizeof line, line); sscanf(line, "%d-%d-%d", &m, &d, &y); printf("\nMonth: %d\nDay: %d\nYear: %d", m, d, y); – T. Daniels Apr 30 '17 at 18:58
0
Try this to use fgets for all input.
The do/while loops will continue until valid input is taken.
This only validates the month. Something should be added to verify day and year.
Check the return of sscanf to make sure the needed items have been successfully scanned.
#include <stdio.h>
int main(){
char line[100] = "";
int scanned = 0;
int valid = 0;
int mm = 0;
int dd = 0;
int yyyy = 0;
int x;
do {
printf("\n\t\t\t1) Input date (mm/dd/yyyy) to find days passed");
printf("\n\t\t\t2) Input passed days to find date in the year");
printf("\n\n\t\t\tYour choice (1/2): ");
if ( !( fgets ( line, sizeof line, stdin))) {
fprintf ( stderr, "problem getting input found EOF\n");
return 1;
}
if ( ( scanned = sscanf(line, "%d", &x)) != 1) {
valid = 0;
}
else {
if ( x == 1 || x == 2) {
valid = 1;
}
else {
valid = 0;
}
}
} while ( !valid);
if(x == 1) {
do {
printf ( "enter date mm-dd-yyyy\n");
if ( !( fgets ( line, sizeof line, stdin))) {
fprintf ( stderr, "problem getting input found EOF\n");
return 1;
}
if ( ( scanned = sscanf ( line, "%d-%d-%d", &mm, &dd, &yyyy)) != 3) {
valid = 0;
}
else {
valid = 1;
//validate the values for mm dd and yyyy
if ( mm < 1 || mm > 12) {
printf ( "invalid month try again\n");
valid = 0;
}
}
} while ( !valid);
}
return 0;
}

xing
- 2,125
- 2
- 14
- 10