c - Sscanf 忽略日期字符串中的日期“-”
问题描述
当我尝试验证代码为的日期字符串的信息时遇到问题
char date[] = "1990-01-01";
sscanf(date, "%d %d %d", &year, &month, &day)
printf("%d-%d-%d", year, month, day);
//expected 1990-01-01
// actual output 1990--1--1
它将“-”字符作为月份和日期的减号,在取值时如何忽略它?我尝试使用 %*- 但它忽略了整数输入提前谢谢
解决方案
您可以尝试使用 sscanf 转换:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char date[] = "1990-01-01";
char year[4];
char month[2];
char day[2];
char m1[1];
char m2[1];
sscanf(date, "%[^-]%[-]%[^-]%[-]%s", year, m1, month, m2, day);
printf("%s %s %s \n", year, month, day);
return 0;
}
执行说:
gcc -o vd -Wall -pedantic -Wextra vd.c
./vd
1990 01 01
这是一个更好的程序,它允许在命令行上进行更多的输入检查:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char year[4];
char month[2];
char day[2];
char m1[1];
char m2[1];
int rc;
if (argc != 2)
{
printf("usage: vd YYYY-MM-DD\n");
return 1;
}
rc = sscanf(argv[1], "%4[0-9^-]%[-]%2[0-9^-]%[-]%2[0-9]",
year, m1, month, m2, day);
if (rc == 5)
printf("%d %d %d \n", atoi(year), atoi(month), atoi(day));
else
{
printf("Incorrect date format\n");
return 1;
}
return 0;
}
执行说:
./vd 1990-01-01
1990 1 1
./vd 1990-12-12
1990 12 12
./vd 1990-01
Incorrect date format
./vd 1990-ab-13
Incorrect date format
这是考虑到@rici 评论的改进版本:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char year[4];
char month[2];
char day[2];
int rc;
if (argc != 2)
{
printf("usage: vd YYYY-MM-DD\n");
return 1;
}
rc = sscanf(argv[1], "%4[0-9]-%2[0-9]-%2[0-9]",
year, month, day);
if (rc == 3)
printf("%d %d %d \n", atoi(year), atoi(month), atoi(day));
else
{
printf("Incorrect date format\n");
return 1;
}
return 0;
}
执行:
./vd 1990-01-02
1990 1 2
./vd 1990-12-12
1990 12 12
./vd 1990-01
Incorrect date format
./vd 1990-db-13
Incorrect date format
./vd 1990--01-02
Incorrect date format
推荐阅读
- mysql - 如何获取具有不同字段的查询输出
- kubernetes - Kubernetes 中没有负载均衡器的 Nginx 入口控制器
- c# - 如何测试对象在特定状态下的状态?
- javascript - 如何在 Cast Receiver Player 中更新过期的 DRM 许可证?
- r - 数据集值替换未产生预期结果
- cordova - Cordova + ngrx/effect fire and forget long running 方法冻结 UI
- javascript - 如何在 Angular 中创建与反应形式一起使用的无线电组件?
- heroku - TypeError:无法读取未定义的属性“缩小”
- java - 如何创建具有不同配置的相同bean
- php - 从循环中的数组中删除重复值