Reputation: 3
#include <stdio.h>
#include <stdio.h>
#include <string.h>
int main(){
char* InputUserDate;
int yyyy;
int mm;
int dd;
printf("Your Date of Birth yyyy-mm-dd:");
scanf("%s",&InputUserDate);
sscanf(InputUserDate, "%d-%d-%d", &yyyy, &mm, &dd);
printf("year: %d, month: %d, day: %d\n", yyyy, mm, dd);
}
This is my code. I want to collect the input of the user in InputUserDate
. I use sscanf
to convert the string to three integers, and to store these in three variables. However, there is no output.
My input: 2000-04-01
and I want the output to be like this :
Year:2000
Month:04
Day:01
Upvotes: 0
Views: 47
Reputation: 26355
char* InputUserDate;
is just an uninitialized pointer - it does not point to any valid memory. You must allocate memory for your string to be written to. One way to do this is by defining an array instead: e.g., char input[32];
.
"%s"
expects a char *
, pointing to valid memory to write to, while &InputUserDate
is of type char **
.
Arrays decay to a pointer-to-the-first-element when used as function arguments -- char input[32]
becomes a char *
when passed to scanf
.
"%s"
should never be used without specifying the maximum field width of the destination buffer - this should be one less than the size of your buffer, to allow room for the NUL terminating byte ('\0'
) that all valid strings in C require.
scanf
and sscanf
can both fail, or partially match the total number of conversions you specify. In either event, the argument's pointed to values can be indeterminate. You must check that the return value of the function matches the number of conversion specifiers you require to be successful, so that the rest of the program operates on valid data.
#include <stdio.h>
#include <string.h>
int main(void) {
char input[32];
int yyyy, mm, dd;
printf("Your Date of Birth yyyy-mm-dd:");
if (scanf("%31s", input) == 1 &&
sscanf(input, "%d-%d-%d", &yyyy, &mm, &dd) == 3) {
printf("year: %d, month: %d, day: %d\n", yyyy, mm, dd);
}
}
Strongly consider using fgets
instead of scanf
to read lines of input, as it allows for better control.
Upvotes: 1