我正在寻找我的问题的解决方案。 我想扫描一个日期 (dd.mm.yyyy)。我需要确保输入是这种格式,只有 0 < day < 31 ; 0 < 月 < 13 ; 2018 < 年 .
对于任务的长度,我是这样做的:
printf("Please typ in the Task: \t");
scanf("%s", &what);
while (strlen(what) >= MAX) {
clearScanf();
printf("The task must contain a maximum of %d :\t", MAX - 1);
scanf("%s", &what);
}
但我不知道如何确保我的
printf("Pls put in the Deadline (dd.mm.yyyy): \t");
scanf("%s", when);
不会使用字符,但仍然使用“.”之间。
在 scanf 之后,我想通过以下方式将所有内容还给我的结构:
strcpy(temp->name, what);
strcpy(temp->deadline, when);
temp->next = pointer;
但我不知道如何返回月、年和日分隔符。
最佳答案
使用scanf
+ sscanf
:
int day, month, year;
for(;;) /* Infinite loop */
{
scanf("%s", when);
char temp;
if(sscanf(when, "%2d.%2d.%4d%c", &day, &month, &year, &temp) != 4 ||
temp != '\n') /* Check if no extra characters were typed after the date */
{
fputs("Invalid format!\n", stderr);
clearScanf(); /* Assuming this function of yours clears the stdin */
}
else if(!(0 < date && date <= 31) || /* Valid range checks */
!(0 < month && month <= 12) ||
!(0 < year && year <= 2018))
{
fputs("Invalid date!\n", stderr);
}
else
{
break;
}
}
它的作用是告诉 scanf
首先扫描一个字符串,然后使用 sscanf
从中提取数据。
sscanf
首先提取 2 个数字,然后是一个点,再提取两个数字,一个点,然后是 4 个数字,最后是一个字符,并分配给相应的参数。该字符用于检查用户是否键入了更多字符。
sscanf
返回成功扫描和分配的项目数。在这种情况下,如果它返回 4,则它成功提取了所有内容。
关于c - 确保 scanf 只读取 dd.mm.yyyy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50812275/