将字符数组转换为时间结构

Convert a char Array to a time structure

本文关键字:时间 结构 转换 字符 数组      更新时间:2023-10-16

>我在当前的项目中使用了一个结构:用于时间信息

struct SFileDateTime
{
uint8 nYear;    // Years since 1900
uint8 nMonth;   // Month [1, 12]
uint8 nDay;     // Day of month [1, 31]
uint8 nHour;    // Hours [0, 23]
uint8 nMinute;  // Minutes [0, 59]
uint8 nSecond;  // Seconds [0, 59]
};
typedef unsigned char           uint8;

在某些情况下,我从外部调用中得到的只是一个日期字符数组

char [17]   "1998012609260000"  

我现在遇到了将字符数组带到 SFileDateTime 结构的问题。我尝试了一个memcpy呼叫,但这会导致崩溃。

我目前不明白为什么 memcpy 不起作用。还有其他方法可以转换它吗? 选角是正确的选择吗?

您在问题下方的评论中有 2 个很棒的答案。希望这对您有所帮助。

typedef unsigned char  uint8; //Max size is 255 in decimal ( 1111 1111 )
struct SFileDateTime
{
uint8 nYear;    // Years since 1900
uint8 nMonth;   // Month [1, 12]
uint8 nDay;     // Day of month [1, 31]
uint8 nHour[20];    // Hours [0, 23]
uint8 nMinute[];  // Minutes [0, 59]
uint8 nSecond;  // Seconds [0, 59]
};

int main()
{
SFileDateTime nene;
nene.nYear = 33;        // ASCII code for       !
nene.nMonth = 'M';      // One char which is 77 in ASCII
nene.nDay = 255;        // max number in ASCII which is space
nene.nSecond = 256 ;     // No go||=== warning: large integer 
//implicitly truncated to      unsigned type [-Woverflow]|
char one[] = "Hello";
cout<<one<<endl;
nene.nHour[0] = 'A';
nene.nHour[1] = 'b';
nene.nHour[2] = 'b';
nene.nHour[3] = 'y';
return 0;
}

如果要使用 strcpytypedef char

如果你想使用你的结构,U应该把它转换为单个字符。

在这里你可以找到一个很好的参考:https://en.cppreference.com/w/c/chrono/localtime