从给定日期提取日、月、年

Extracting day,month,year from a given date

本文关键字:取日 提取 日期      更新时间:2023-10-16

我试图使用sscanf从给定日期中提取日、月、年,但似乎不起作用。这是我的一段代码。。。

我已将日期存储在一个字符数组中。

void dateinp(char date[])
{
     char d[5];
     char y[5];
     char mm[5];
     sscanf(date,"%s-%s-%s",d,mm,y);
     printf("%sn%sn%sn",d,mm,y);
}

我哪里错了?

2015年1月12日输入时,我得到:2015年1月12日-2015年1月12日N-20155

您的代码位于C中,而问题标记为C++。这是一个C++版本:

// accepts 12-JAN-2015
void dateinp(const string& date)
{
    string d = date.substr(0, 2);
    string mm = date.substr(3, 3);
    string y = date.substr(7, 4);
    cout << d << "/" << mm << "/" << y << endl;
}

另一个版本是:

#include <sstream>
#include <iostream>
using namespace std;
// accepts 12-JAN-2015, also accepts 2-JAN-2015 (where the day is just a single digit)
void dateinp(const string& date)
{
    stringstream ss(date);
    string d, mm, y;
    getline(ss, d, '-');
    getline(ss, mm, '-');
    getline(ss, y, '-');
    cout << d << "/" << mm << "/" << y << endl;
}
int day, month, year;
sscanf(buffer, "%2d/%2d/%4d",
    &month,
    &day,
    &year);