I want to create a simple "date" using sscanfthat accepts input as:
"dd/mm/yyyy"
Both fields "dd" and "mm" can be equal to 2 bits (for example, 0, 6 or 11, but not 123). The years field may be a 0 or 4 digit field. A value of 0 in any of these three fields means that you should instead accept the day, month, or year of the system.
This format must be strict, therefore, if the input format does not match the template, the user must be notified.
My attempt:
int d, m, y;
char const* input = "23/7/1990";
int n = sscanf(input, "%2u/%2u/%4u", &d, &m, &y);
if (n != 3) throw InvalidDate("Invalid format");
// Fill 0 values with system date.
// Check date correctness with `mktime` and `localtime`.
The problem is that this format sscanfaccepts invalid inputs like:
char const* invalid1 = "23/ 12/ 1990";
char const* invalid2 = "23/12/1990/123whatever......."
, - / , ?
(invalid2; ) :
int d, m, y;
char trick;
char const* input = "23/7/1990";
int n = sscanf(input, "%2u/%2u/%4u%c", &d, &m, &y, &trick);
if (fields != 3) throw InvalidDate("Invalid format");
, end-of-string. , "" ( "% c" ) sscanf, , (, "23/6/1990" char ; if scanf sscanf, ferror ). "%2u/%2u/%4u\0", \0 .
, stringstream?
, "" sscanf?