首页 > 解决方案 > 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

它将“-”字符作为月份和日期的减号,在取值时如何忽略它?我尝试使用 %*- 但它忽略了整数输入提前谢谢

标签: cstringparsingscanf

解决方案


您可以尝试使用 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

推荐阅读